@rvaim/deveco-mobile-mcp 0.1.0-rvaim.1
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/LICENSE +201 -0
- package/NOTICE +15 -0
- package/README.md +129 -0
- package/lib/android.js +596 -0
- package/lib/harmony.js +805 -0
- package/lib/image-utils.js +155 -0
- package/lib/index.js +60 -0
- package/lib/ios.js +282 -0
- package/lib/iphone-simulator.js +266 -0
- package/lib/jpeg.js +48 -0
- package/lib/logger.js +22 -0
- package/lib/mobile-device.js +159 -0
- package/lib/mobilecli.js +112 -0
- package/lib/png.js +19 -0
- package/lib/robot.js +9 -0
- package/lib/server.js +615 -0
- package/lib/utils.js +80 -0
- package/lib/webdriver-agent.js +399 -0
- package/package.json +86 -0
package/lib/server.js
ADDED
|
@@ -0,0 +1,615 @@
|
|
|
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 harmony_1 = require("./harmony");
|
|
18
|
+
const png_1 = require("./png");
|
|
19
|
+
const jpeg_1 = require("./jpeg");
|
|
20
|
+
const image_utils_1 = require("./image-utils");
|
|
21
|
+
const mobilecli_1 = require("./mobilecli");
|
|
22
|
+
const mobile_device_1 = require("./mobile-device");
|
|
23
|
+
const utils_1 = require("./utils");
|
|
24
|
+
const ALLOWED_SCREENSHOT_EXTENSIONS = [".png", ".jpg", ".jpeg"];
|
|
25
|
+
const ALLOWED_RECORDING_EXTENSIONS = [".mp4"];
|
|
26
|
+
const getAgentVersion = () => {
|
|
27
|
+
const json = require("../package.json");
|
|
28
|
+
return json.version;
|
|
29
|
+
};
|
|
30
|
+
exports.getAgentVersion = getAgentVersion;
|
|
31
|
+
const createMcpServer = () => {
|
|
32
|
+
const server = new mcp_js_1.McpServer({
|
|
33
|
+
name: "mobile-mcp",
|
|
34
|
+
version: (0, exports.getAgentVersion)(),
|
|
35
|
+
});
|
|
36
|
+
const getClientName = () => {
|
|
37
|
+
try {
|
|
38
|
+
const clientInfo = server.server.getClientVersion();
|
|
39
|
+
const clientName = clientInfo?.name || "unknown";
|
|
40
|
+
return clientName;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
return "unknown";
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const tool = (name, title, description, paramsSchema, annotations, cb) => {
|
|
47
|
+
server.registerTool(name, {
|
|
48
|
+
title,
|
|
49
|
+
description,
|
|
50
|
+
inputSchema: paramsSchema,
|
|
51
|
+
annotations,
|
|
52
|
+
}, (async (args, _extra) => {
|
|
53
|
+
try {
|
|
54
|
+
(0, logger_1.trace)(`Invoking ${name} with args: ${JSON.stringify(args)}`);
|
|
55
|
+
const start = +new Date();
|
|
56
|
+
const response = await cb(args);
|
|
57
|
+
const duration = +new Date() - start;
|
|
58
|
+
(0, logger_1.trace)(`=> ${response}`);
|
|
59
|
+
posthog("tool_invoked", { "ToolName": name, "Duration": duration }).then();
|
|
60
|
+
return {
|
|
61
|
+
content: [{ type: "text", text: response }],
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
posthog("tool_failed", { "ToolName": name }).then();
|
|
66
|
+
if (error instanceof robot_1.ActionableError) {
|
|
67
|
+
return {
|
|
68
|
+
content: [{ type: "text", text: `${error.message}. Please fix the issue and try again.` }],
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
// a real exception
|
|
73
|
+
(0, logger_1.trace)(`Tool '${description}' failed: ${error.message} stack: ${error.stack}`);
|
|
74
|
+
return {
|
|
75
|
+
content: [{ type: "text", text: `Error: ${error.message}` }],
|
|
76
|
+
isError: true,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}));
|
|
81
|
+
};
|
|
82
|
+
const posthog = async (event, properties) => {
|
|
83
|
+
try {
|
|
84
|
+
const url = "https://us.i.posthog.com/i/v0/e/";
|
|
85
|
+
const api_key = "phc_KHRTZmkDsU7A8EbydEK8s4lJpPoTDyyBhSlwer694cS";
|
|
86
|
+
const name = node_os_1.default.hostname() + process.execPath;
|
|
87
|
+
const distinct_id = node_crypto_1.default.createHash("sha256").update(name).digest("hex");
|
|
88
|
+
const systemProps = {
|
|
89
|
+
Platform: node_os_1.default.platform(),
|
|
90
|
+
Product: "mobile-mcp",
|
|
91
|
+
Version: (0, exports.getAgentVersion)(),
|
|
92
|
+
NodeVersion: process.version,
|
|
93
|
+
};
|
|
94
|
+
const clientName = getClientName();
|
|
95
|
+
if (clientName !== "unknown") {
|
|
96
|
+
systemProps.AgentName = clientName;
|
|
97
|
+
}
|
|
98
|
+
await fetch(url, {
|
|
99
|
+
method: "POST",
|
|
100
|
+
headers: {
|
|
101
|
+
"Content-Type": "application/json"
|
|
102
|
+
},
|
|
103
|
+
body: JSON.stringify({
|
|
104
|
+
api_key,
|
|
105
|
+
event,
|
|
106
|
+
properties: {
|
|
107
|
+
...systemProps,
|
|
108
|
+
...properties,
|
|
109
|
+
},
|
|
110
|
+
distinct_id,
|
|
111
|
+
})
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
// ignore
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
const mobilecli = new mobilecli_1.Mobilecli();
|
|
119
|
+
const activeRecordings = new Map();
|
|
120
|
+
posthog("launch", {}).then();
|
|
121
|
+
const ensureMobilecliAvailable = () => {
|
|
122
|
+
try {
|
|
123
|
+
const version = mobilecli.getVersion();
|
|
124
|
+
if (version.startsWith("failed")) {
|
|
125
|
+
throw new Error("mobilecli version check failed");
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
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`);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
const isHarmonyDevice = (deviceId) => {
|
|
133
|
+
const harmonyManager = new harmony_1.HarmonyDeviceManager();
|
|
134
|
+
const harmonyDevices = harmonyManager.getConnectedDevices();
|
|
135
|
+
return harmonyDevices.some(d => d.deviceId === deviceId);
|
|
136
|
+
};
|
|
137
|
+
const getRobotFromDevice = (deviceId) => {
|
|
138
|
+
// from now on, we must have mobilecli working
|
|
139
|
+
ensureMobilecliAvailable();
|
|
140
|
+
// Check if it's a HarmonyOS device (emulator or real device)
|
|
141
|
+
const harmonyManager = new harmony_1.HarmonyDeviceManager();
|
|
142
|
+
const harmonyDevices = harmonyManager.getConnectedDevices();
|
|
143
|
+
const harmonyDevice = harmonyDevices.find(d => d.deviceId === deviceId);
|
|
144
|
+
if (harmonyDevice) {
|
|
145
|
+
return new harmony_1.HarmonyRobot(deviceId);
|
|
146
|
+
}
|
|
147
|
+
// Check if it's an iOS device
|
|
148
|
+
const iosManager = new ios_1.IosManager();
|
|
149
|
+
const iosDevices = iosManager.listDevices();
|
|
150
|
+
const iosDevice = iosDevices.find(d => d.deviceId === deviceId);
|
|
151
|
+
if (iosDevice) {
|
|
152
|
+
return new ios_1.IosRobot(deviceId);
|
|
153
|
+
}
|
|
154
|
+
// Check if it's an Android device
|
|
155
|
+
const androidManager = new android_1.AndroidDeviceManager();
|
|
156
|
+
const androidDevices = androidManager.getConnectedDevices();
|
|
157
|
+
const androidDevice = androidDevices.find(d => d.deviceId === deviceId);
|
|
158
|
+
if (androidDevice) {
|
|
159
|
+
return new android_1.AndroidRobot(deviceId);
|
|
160
|
+
}
|
|
161
|
+
// Check if it's a simulator (will later replace all other device types as well)
|
|
162
|
+
const response = mobilecli.getDevices({
|
|
163
|
+
platform: "ios",
|
|
164
|
+
type: "simulator",
|
|
165
|
+
includeOffline: false,
|
|
166
|
+
});
|
|
167
|
+
if (response.status === "ok" && response.data && response.data.devices) {
|
|
168
|
+
for (const device of response.data.devices) {
|
|
169
|
+
if (device.id === deviceId) {
|
|
170
|
+
return new mobile_device_1.MobileDevice(deviceId);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
throw new robot_1.ActionableError(`Device "${deviceId}" not found. Use of mobile_list_available_devices tool to see available devices.`);
|
|
175
|
+
};
|
|
176
|
+
tool("mobile_list_available_devices", "List Devices", "List all available devices. This includes both physical mobile devices and mobile simulators and emulators. It returns Android, iOS, and HarmonyOS devices.\n\nFor HarmonyOS emulators that are offline, use mobile_start_emulator to start them.", {}, { readOnlyHint: true }, async ({}) => {
|
|
177
|
+
// from today onward, we must have mobilecli working
|
|
178
|
+
ensureMobilecliAvailable();
|
|
179
|
+
const iosManager = new ios_1.IosManager();
|
|
180
|
+
const androidManager = new android_1.AndroidDeviceManager();
|
|
181
|
+
const harmonyManager = new harmony_1.HarmonyDeviceManager();
|
|
182
|
+
const devices = [];
|
|
183
|
+
// Get HarmonyOS devices (emulators and real devices)
|
|
184
|
+
try {
|
|
185
|
+
const harmonyDevices = harmonyManager.getAllAvailableDevices();
|
|
186
|
+
for (const device of harmonyDevices) {
|
|
187
|
+
devices.push({
|
|
188
|
+
id: device.deviceId,
|
|
189
|
+
name: device.name,
|
|
190
|
+
platform: "harmonyos",
|
|
191
|
+
type: device.deviceType,
|
|
192
|
+
version: device.version,
|
|
193
|
+
state: device.deviceId ? "online" : "offline",
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
// If HarmonyOS tools are not available, silently skip
|
|
199
|
+
}
|
|
200
|
+
// Get Android devices with details
|
|
201
|
+
const androidDevices = androidManager.getConnectedDevicesWithDetails();
|
|
202
|
+
for (const device of androidDevices) {
|
|
203
|
+
devices.push({
|
|
204
|
+
id: device.deviceId,
|
|
205
|
+
name: device.name,
|
|
206
|
+
platform: "android",
|
|
207
|
+
type: "emulator",
|
|
208
|
+
version: device.version,
|
|
209
|
+
state: "online",
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
// Get iOS physical devices with details
|
|
213
|
+
try {
|
|
214
|
+
const iosDevices = iosManager.listDevicesWithDetails();
|
|
215
|
+
for (const device of iosDevices) {
|
|
216
|
+
devices.push({
|
|
217
|
+
id: device.deviceId,
|
|
218
|
+
name: device.deviceName,
|
|
219
|
+
platform: "ios",
|
|
220
|
+
type: "real",
|
|
221
|
+
version: device.version,
|
|
222
|
+
state: "online",
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
// If go-ios is not available, silently skip
|
|
228
|
+
}
|
|
229
|
+
// Get iOS simulators from mobilecli (excluding offline devices)
|
|
230
|
+
const response = mobilecli.getDevices({
|
|
231
|
+
platform: "ios",
|
|
232
|
+
type: "simulator",
|
|
233
|
+
includeOffline: false,
|
|
234
|
+
});
|
|
235
|
+
if (response.status === "ok" && response.data && response.data.devices) {
|
|
236
|
+
for (const device of response.data.devices) {
|
|
237
|
+
devices.push({
|
|
238
|
+
id: device.id,
|
|
239
|
+
name: device.name,
|
|
240
|
+
platform: device.platform,
|
|
241
|
+
type: device.type,
|
|
242
|
+
version: device.version,
|
|
243
|
+
state: "online",
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const out = { devices };
|
|
248
|
+
return JSON.stringify(out);
|
|
249
|
+
});
|
|
250
|
+
tool("mobile_start_emulator", "Start Emulator", "Start a HarmonyOS emulator by name. Use mobile_list_available_devices to see available emulators.", {
|
|
251
|
+
name: zod_1.z.string().describe("The name of the emulator to start (e.g., 'Enjoy 90 Pro Max')"),
|
|
252
|
+
}, { destructiveHint: true }, async ({ name }) => {
|
|
253
|
+
const harmonyManager = new harmony_1.HarmonyDeviceManager();
|
|
254
|
+
const deviceId = await harmonyManager.startEmulator(name);
|
|
255
|
+
if (deviceId) {
|
|
256
|
+
return `Emulator "${name}" started successfully. Device ID: ${deviceId}`;
|
|
257
|
+
}
|
|
258
|
+
return `Emulator "${name}" started but device ID was not returned. It may still be booting.`;
|
|
259
|
+
});
|
|
260
|
+
if (process.env.MOBILEFLEET_ENABLE === "1") {
|
|
261
|
+
tool("mobile_list_fleet_devices", "List Fleet Devices", "List devices available in the remote fleet", {}, { readOnlyHint: true }, async ({}) => {
|
|
262
|
+
ensureMobilecliAvailable();
|
|
263
|
+
const result = mobilecli.fleetListDevices();
|
|
264
|
+
return result;
|
|
265
|
+
});
|
|
266
|
+
tool("mobile_allocate_fleet_device", "Allocate Fleet Device", "Reserve a device from the remote fleet", {
|
|
267
|
+
platform: zod_1.z.enum(["ios", "android"]).describe("The platform to allocate a device for"),
|
|
268
|
+
}, { destructiveHint: true }, async ({ platform }) => {
|
|
269
|
+
ensureMobilecliAvailable();
|
|
270
|
+
const result = mobilecli.fleetAllocate(platform);
|
|
271
|
+
return result;
|
|
272
|
+
});
|
|
273
|
+
tool("mobile_release_fleet_device", "Release Fleet Device", "Release a device back to the remote fleet", {
|
|
274
|
+
device: zod_1.z.string().describe("The device identifier to release back to the fleet"),
|
|
275
|
+
}, { destructiveHint: true }, async ({ device }) => {
|
|
276
|
+
ensureMobilecliAvailable();
|
|
277
|
+
const result = mobilecli.fleetRelease(device);
|
|
278
|
+
return result;
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
tool("mobile_list_apps", "List Apps", "List all the installed apps on the device", {
|
|
282
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
|
|
283
|
+
}, { readOnlyHint: true }, async ({ device }) => {
|
|
284
|
+
const robot = getRobotFromDevice(device);
|
|
285
|
+
const result = await robot.listApps();
|
|
286
|
+
return `Found these apps on device: ${result.map(app => `${app.appName} (${app.packageName})`).join(", ")}`;
|
|
287
|
+
});
|
|
288
|
+
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.", {
|
|
289
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
290
|
+
packageName: zod_1.z.string().describe("The package name of the app to launch"),
|
|
291
|
+
locale: zod_1.z.string().optional().describe("Comma-separated BCP 47 locale tags to launch the app with (e.g., fr-FR,en-GB)"),
|
|
292
|
+
}, { destructiveHint: true }, async ({ device, packageName, locale }) => {
|
|
293
|
+
const robot = getRobotFromDevice(device);
|
|
294
|
+
await robot.launchApp(packageName, locale);
|
|
295
|
+
return `Launched app ${packageName}`;
|
|
296
|
+
});
|
|
297
|
+
tool("mobile_terminate_app", "Terminate App", "Stop and terminate an app on mobile device", {
|
|
298
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
299
|
+
packageName: zod_1.z.string().describe("The package name of the app to terminate"),
|
|
300
|
+
}, { destructiveHint: true }, async ({ device, packageName }) => {
|
|
301
|
+
const robot = getRobotFromDevice(device);
|
|
302
|
+
await robot.terminateApp(packageName);
|
|
303
|
+
return `Terminated app ${packageName}`;
|
|
304
|
+
});
|
|
305
|
+
tool("mobile_install_app", "Install App", "Install an app on mobile device", {
|
|
306
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
307
|
+
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"),
|
|
308
|
+
}, { destructiveHint: true }, async ({ device, path }) => {
|
|
309
|
+
const robot = getRobotFromDevice(device);
|
|
310
|
+
await robot.installApp(path);
|
|
311
|
+
return `Installed app from ${path}`;
|
|
312
|
+
});
|
|
313
|
+
tool("mobile_uninstall_app", "Uninstall App", "Uninstall an app from mobile device", {
|
|
314
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
315
|
+
bundle_id: zod_1.z.string().describe("Bundle identifier (iOS) or package name (Android) of the app to be uninstalled"),
|
|
316
|
+
}, { destructiveHint: true }, async ({ device, bundle_id }) => {
|
|
317
|
+
const robot = getRobotFromDevice(device);
|
|
318
|
+
await robot.uninstallApp(bundle_id);
|
|
319
|
+
return `Uninstalled app ${bundle_id}`;
|
|
320
|
+
});
|
|
321
|
+
tool("mobile_get_screen_size", "Get Screen Size", "Get the screen size of the mobile device in pixels", {
|
|
322
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
|
|
323
|
+
}, { readOnlyHint: true }, async ({ device }) => {
|
|
324
|
+
const robot = getRobotFromDevice(device);
|
|
325
|
+
const screenSize = await robot.getScreenSize();
|
|
326
|
+
return `Screen size is ${screenSize.width}x${screenSize.height} pixels`;
|
|
327
|
+
});
|
|
328
|
+
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.", {
|
|
329
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
330
|
+
x: zod_1.z.coerce.number().describe("The x coordinate to click on the screen, in pixels"),
|
|
331
|
+
y: zod_1.z.coerce.number().describe("The y coordinate to click on the screen, in pixels"),
|
|
332
|
+
}, { destructiveHint: true }, async ({ device, x, y }) => {
|
|
333
|
+
const robot = getRobotFromDevice(device);
|
|
334
|
+
await robot.tap(x, y);
|
|
335
|
+
return `Clicked on screen at coordinates: ${x}, ${y}`;
|
|
336
|
+
});
|
|
337
|
+
tool("mobile_double_tap_on_screen", "Double Tap Screen", "Double-tap on the screen at given x,y coordinates.", {
|
|
338
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
339
|
+
x: zod_1.z.coerce.number().describe("The x coordinate to double-tap, in pixels"),
|
|
340
|
+
y: zod_1.z.coerce.number().describe("The y coordinate to double-tap, in pixels"),
|
|
341
|
+
}, { destructiveHint: true }, async ({ device, x, y }) => {
|
|
342
|
+
const robot = getRobotFromDevice(device);
|
|
343
|
+
await robot.doubleTap(x, y);
|
|
344
|
+
return `Double-tapped on screen at coordinates: ${x}, ${y}`;
|
|
345
|
+
});
|
|
346
|
+
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.", {
|
|
347
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
348
|
+
x: zod_1.z.coerce.number().describe("The x coordinate to long press on the screen, in pixels"),
|
|
349
|
+
y: zod_1.z.coerce.number().describe("The y coordinate to long press on the screen, in pixels"),
|
|
350
|
+
duration: zod_1.z.coerce.number().min(1).max(10000).optional().describe("Duration of the long press in milliseconds. Defaults to 500ms."),
|
|
351
|
+
}, { destructiveHint: true }, async ({ device, x, y, duration }) => {
|
|
352
|
+
const robot = getRobotFromDevice(device);
|
|
353
|
+
const pressDuration = duration ?? 500;
|
|
354
|
+
await robot.longPress(x, y, pressDuration);
|
|
355
|
+
return `Long pressed on screen at coordinates: ${x}, ${y} for ${pressDuration}ms`;
|
|
356
|
+
});
|
|
357
|
+
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.", {
|
|
358
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
|
|
359
|
+
}, { readOnlyHint: true }, async ({ device }) => {
|
|
360
|
+
const robot = getRobotFromDevice(device);
|
|
361
|
+
const result = await robot.getElementsOnScreen();
|
|
362
|
+
// For HarmonyOS, result is a file path to the raw hidumper dump
|
|
363
|
+
if (typeof result === "string") {
|
|
364
|
+
return `Elements saved to file: ${result}`;
|
|
365
|
+
}
|
|
366
|
+
// For other platforms, format as JSON array
|
|
367
|
+
const formattedResult = result.map(element => {
|
|
368
|
+
const out = {
|
|
369
|
+
type: element.type,
|
|
370
|
+
text: element.text,
|
|
371
|
+
label: element.label,
|
|
372
|
+
name: element.name,
|
|
373
|
+
value: element.value,
|
|
374
|
+
identifier: element.identifier,
|
|
375
|
+
coordinates: {
|
|
376
|
+
x: element.rect.x,
|
|
377
|
+
y: element.rect.y,
|
|
378
|
+
width: element.rect.width,
|
|
379
|
+
height: element.rect.height,
|
|
380
|
+
},
|
|
381
|
+
};
|
|
382
|
+
if (element.focused) {
|
|
383
|
+
out.focused = true;
|
|
384
|
+
}
|
|
385
|
+
return out;
|
|
386
|
+
});
|
|
387
|
+
return `Found these elements on screen: ${JSON.stringify(formattedResult)}`;
|
|
388
|
+
});
|
|
389
|
+
tool("mobile_press_button", "Press Button", "Press a button on device", {
|
|
390
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
391
|
+
button: zod_1.z.string().describe("The button to press. Supported buttons: BACK (android only), HOME, VOLUME_UP, VOLUME_DOWN, ENTER, DEL, 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)"),
|
|
392
|
+
}, { destructiveHint: true }, async ({ device, button }) => {
|
|
393
|
+
const robot = getRobotFromDevice(device);
|
|
394
|
+
await robot.pressButton(button);
|
|
395
|
+
return `Pressed the button: ${button}`;
|
|
396
|
+
});
|
|
397
|
+
tool("mobile_open_url", "Open URL", "Open a URL in browser on device", {
|
|
398
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
399
|
+
url: zod_1.z.string().describe("The URL to open"),
|
|
400
|
+
}, { destructiveHint: true }, async ({ device, url }) => {
|
|
401
|
+
// HarmonyOS 设备支持自定义 URL scheme(如 alipays://),跳过检查
|
|
402
|
+
const isHarmony = isHarmonyDevice(device);
|
|
403
|
+
const allowUnsafeUrls = process.env.MOBILEMCP_ALLOW_UNSAFE_URLS === "1";
|
|
404
|
+
if (!isHarmony && !allowUnsafeUrls && !url.startsWith("http://") && !url.startsWith("https://")) {
|
|
405
|
+
throw new robot_1.ActionableError("Only http:// and https:// URLs are allowed. Set MOBILEMCP_ALLOW_UNSAFE_URLS=1 to allow other URL schemes.");
|
|
406
|
+
}
|
|
407
|
+
const robot = getRobotFromDevice(device);
|
|
408
|
+
await robot.openUrl(url);
|
|
409
|
+
return `Opened URL: ${url}`;
|
|
410
|
+
});
|
|
411
|
+
tool("mobile_swipe_on_screen", "Swipe Screen", "Swipe on the screen", {
|
|
412
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
413
|
+
direction: zod_1.z.enum(["up", "down", "left", "right"]).describe("The direction to swipe"),
|
|
414
|
+
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"),
|
|
415
|
+
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"),
|
|
416
|
+
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"),
|
|
417
|
+
}, { destructiveHint: true }, async ({ device, direction, x, y, distance }) => {
|
|
418
|
+
const robot = getRobotFromDevice(device);
|
|
419
|
+
if (x !== undefined && y !== undefined) {
|
|
420
|
+
// Use coordinate-based swipe
|
|
421
|
+
await robot.swipeFromCoordinate(x, y, direction, distance);
|
|
422
|
+
const distanceText = distance ? ` ${distance} pixels` : "";
|
|
423
|
+
return `Swiped ${direction}${distanceText} from coordinates: ${x}, ${y}`;
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
// Use center-based swipe
|
|
427
|
+
await robot.swipe(direction);
|
|
428
|
+
return `Swiped ${direction} on screen`;
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
tool("mobile_type_keys", "Type Text", "Type text into the focused element. For HarmonyOS devices, x and y coordinates are REQUIRED to specify the input position. For iOS/Android, coordinates are optional as text is input to the currently focused element.", {
|
|
432
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
433
|
+
text: zod_1.z.string().describe("The text to type"),
|
|
434
|
+
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."),
|
|
435
|
+
x: zod_1.z.number().optional().describe("Optional x coordinate for input position (REQUIRED for HarmonyOS). Use the same coordinates as the input field."),
|
|
436
|
+
y: zod_1.z.number().optional().describe("Optional y coordinate for input position (REQUIRED for HarmonyOS). Use the same coordinates as the input field."),
|
|
437
|
+
}, { destructiveHint: true }, async ({ device, text, submit, x, y }) => {
|
|
438
|
+
const robot = getRobotFromDevice(device);
|
|
439
|
+
await robot.sendKeys(text, x, y);
|
|
440
|
+
if (submit) {
|
|
441
|
+
await robot.pressButton("ENTER");
|
|
442
|
+
}
|
|
443
|
+
return `Typed text: ${text}${x !== undefined && y !== undefined ? ` at position (${x}, ${y})` : ""}`;
|
|
444
|
+
});
|
|
445
|
+
tool("mobile_save_screenshot", "Save Screenshot", "Save a screenshot of the mobile device to a file", {
|
|
446
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
447
|
+
saveTo: zod_1.z.string().describe("The path to save the screenshot to. Filename must end with .png, .jpg, or .jpeg"),
|
|
448
|
+
}, { destructiveHint: true }, async ({ device, saveTo }) => {
|
|
449
|
+
(0, utils_1.validateFileExtension)(saveTo, ALLOWED_SCREENSHOT_EXTENSIONS, "save_screenshot");
|
|
450
|
+
(0, utils_1.validateOutputPath)(saveTo);
|
|
451
|
+
const robot = getRobotFromDevice(device);
|
|
452
|
+
const screenshot = await robot.getScreenshot();
|
|
453
|
+
node_fs_1.default.writeFileSync(saveTo, screenshot);
|
|
454
|
+
return `Screenshot saved to: ${saveTo}`;
|
|
455
|
+
});
|
|
456
|
+
server.registerTool("mobile_take_screenshot", {
|
|
457
|
+
title: "Take Screenshot",
|
|
458
|
+
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.",
|
|
459
|
+
inputSchema: {
|
|
460
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
|
|
461
|
+
},
|
|
462
|
+
annotations: {
|
|
463
|
+
readOnlyHint: true,
|
|
464
|
+
},
|
|
465
|
+
}, async ({ device }) => {
|
|
466
|
+
try {
|
|
467
|
+
const robot = getRobotFromDevice(device);
|
|
468
|
+
const isHarmony = isHarmonyDevice(device);
|
|
469
|
+
let screenshot = await robot.getScreenshot();
|
|
470
|
+
let mimeType = "image/png";
|
|
471
|
+
let imageWidth;
|
|
472
|
+
let imageHeight;
|
|
473
|
+
if (isHarmony) {
|
|
474
|
+
// HarmonyOS returns JPEG directly
|
|
475
|
+
mimeType = "image/jpeg";
|
|
476
|
+
const jpeg = new jpeg_1.JPEG(screenshot);
|
|
477
|
+
const jpegSize = jpeg.getDimensions();
|
|
478
|
+
if (jpegSize.width <= 0 || jpegSize.height <= 0) {
|
|
479
|
+
throw new robot_1.ActionableError("Screenshot is invalid. Please try again.");
|
|
480
|
+
}
|
|
481
|
+
imageWidth = jpegSize.width;
|
|
482
|
+
imageHeight = jpegSize.height;
|
|
483
|
+
}
|
|
484
|
+
else {
|
|
485
|
+
// iOS and Android return PNG
|
|
486
|
+
const screenSize = await robot.getScreenSize();
|
|
487
|
+
const image = new png_1.PNG(screenshot);
|
|
488
|
+
const pngSize = image.getDimensions();
|
|
489
|
+
if (pngSize.width <= 0 || pngSize.height <= 0) {
|
|
490
|
+
throw new robot_1.ActionableError("Screenshot is invalid. Please try again.");
|
|
491
|
+
}
|
|
492
|
+
imageWidth = pngSize.width;
|
|
493
|
+
imageHeight = pngSize.height;
|
|
494
|
+
if ((0, image_utils_1.isScalingAvailable)()) {
|
|
495
|
+
(0, logger_1.trace)("Image scaling is available, resizing screenshot");
|
|
496
|
+
const img = image_utils_1.Image.fromBuffer(screenshot);
|
|
497
|
+
const beforeSize = screenshot.length;
|
|
498
|
+
screenshot = img.resize(Math.floor(pngSize.width / screenSize.scale))
|
|
499
|
+
.jpeg({ quality: 75 })
|
|
500
|
+
.toBuffer();
|
|
501
|
+
const afterSize = screenshot.length;
|
|
502
|
+
(0, logger_1.trace)(`Screenshot resized from ${beforeSize} bytes to ${afterSize} bytes`);
|
|
503
|
+
mimeType = "image/jpeg";
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const screenshot64 = screenshot.toString("base64");
|
|
507
|
+
(0, logger_1.trace)(`Screenshot taken: ${screenshot.length} bytes`);
|
|
508
|
+
posthog("tool_invoked", {
|
|
509
|
+
"ToolName": "mobile_take_screenshot",
|
|
510
|
+
"ScreenshotFilesize": screenshot64.length,
|
|
511
|
+
"ScreenshotMimeType": mimeType,
|
|
512
|
+
"ScreenshotWidth": imageWidth,
|
|
513
|
+
"ScreenshotHeight": imageHeight,
|
|
514
|
+
}).then();
|
|
515
|
+
return {
|
|
516
|
+
content: [{ type: "image", data: screenshot64, mimeType }]
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
catch (err) {
|
|
520
|
+
(0, logger_1.error)(`Error taking screenshot: ${err.message} ${err.stack}`);
|
|
521
|
+
return {
|
|
522
|
+
content: [{ type: "text", text: `Error: ${err.message}` }],
|
|
523
|
+
isError: true,
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
});
|
|
527
|
+
tool("mobile_set_orientation", "Set Orientation", "Change the screen orientation of the device", {
|
|
528
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
529
|
+
orientation: zod_1.z.enum(["portrait", "landscape"]).describe("The desired orientation"),
|
|
530
|
+
}, { destructiveHint: true }, async ({ device, orientation }) => {
|
|
531
|
+
const robot = getRobotFromDevice(device);
|
|
532
|
+
await robot.setOrientation(orientation);
|
|
533
|
+
return `Changed device orientation to ${orientation}`;
|
|
534
|
+
});
|
|
535
|
+
tool("mobile_get_orientation", "Get Orientation", "Get the current screen orientation of the device", {
|
|
536
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
|
|
537
|
+
}, { readOnlyHint: true }, async ({ device }) => {
|
|
538
|
+
const robot = getRobotFromDevice(device);
|
|
539
|
+
const orientation = await robot.getOrientation();
|
|
540
|
+
return `Current device orientation is ${orientation}`;
|
|
541
|
+
});
|
|
542
|
+
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.", {
|
|
543
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
544
|
+
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."),
|
|
545
|
+
timeLimit: zod_1.z.coerce.number().optional().describe("Maximum recording duration in seconds. The recording will stop automatically after this time."),
|
|
546
|
+
}, { destructiveHint: true }, async ({ device, output, timeLimit }) => {
|
|
547
|
+
if (output) {
|
|
548
|
+
(0, utils_1.validateFileExtension)(output, ALLOWED_RECORDING_EXTENSIONS, "start_screen_recording");
|
|
549
|
+
(0, utils_1.validateOutputPath)(output);
|
|
550
|
+
}
|
|
551
|
+
getRobotFromDevice(device);
|
|
552
|
+
if (activeRecordings.has(device)) {
|
|
553
|
+
throw new robot_1.ActionableError(`Device "${device}" is already being recorded. Stop the current recording first with mobile_stop_screen_recording.`);
|
|
554
|
+
}
|
|
555
|
+
const outputPath = output || node_path_1.default.join(node_os_1.default.tmpdir(), `screen-recording-${Date.now()}.mp4`);
|
|
556
|
+
const args = ["screenrecord", "--device", device, "--output", outputPath, "--silent"];
|
|
557
|
+
if (timeLimit !== undefined) {
|
|
558
|
+
args.push("--time-limit", String(timeLimit));
|
|
559
|
+
}
|
|
560
|
+
const child = mobilecli.spawnCommand(args);
|
|
561
|
+
const cleanup = () => {
|
|
562
|
+
activeRecordings.delete(device);
|
|
563
|
+
};
|
|
564
|
+
child.on("error", cleanup);
|
|
565
|
+
child.on("exit", cleanup);
|
|
566
|
+
activeRecordings.set(device, {
|
|
567
|
+
process: child,
|
|
568
|
+
outputPath,
|
|
569
|
+
startedAt: Date.now(),
|
|
570
|
+
});
|
|
571
|
+
return `Screen recording started. Output will be saved to: ${outputPath}`;
|
|
572
|
+
});
|
|
573
|
+
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.", {
|
|
574
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
575
|
+
}, { destructiveHint: true }, async ({ device }) => {
|
|
576
|
+
const recording = activeRecordings.get(device);
|
|
577
|
+
if (!recording) {
|
|
578
|
+
throw new robot_1.ActionableError(`No active recording found for device "${device}". Start a recording first with mobile_start_screen_recording.`);
|
|
579
|
+
}
|
|
580
|
+
const { process: child, outputPath, startedAt } = recording;
|
|
581
|
+
activeRecordings.delete(device);
|
|
582
|
+
child.kill("SIGINT");
|
|
583
|
+
await new Promise(resolve => {
|
|
584
|
+
const timeout = setTimeout(() => {
|
|
585
|
+
child.kill("SIGKILL");
|
|
586
|
+
resolve();
|
|
587
|
+
}, 5 * 60 * 1000);
|
|
588
|
+
child.on("close", () => {
|
|
589
|
+
clearTimeout(timeout);
|
|
590
|
+
resolve();
|
|
591
|
+
});
|
|
592
|
+
});
|
|
593
|
+
const durationSeconds = Math.round((Date.now() - startedAt) / 1000);
|
|
594
|
+
if (!node_fs_1.default.existsSync(outputPath)) {
|
|
595
|
+
return `Recording stopped after ~${durationSeconds}s but the output file was not found at: ${outputPath}`;
|
|
596
|
+
}
|
|
597
|
+
const stats = node_fs_1.default.statSync(outputPath);
|
|
598
|
+
const fileSizeMB = (stats.size / (1024 * 1024)).toFixed(2);
|
|
599
|
+
return `Recording stopped. File: ${outputPath} (${fileSizeMB} MB, ~${durationSeconds}s)`;
|
|
600
|
+
});
|
|
601
|
+
tool("mobile_get_device_logs", "Get Device Logs", "Get device logs (hilog for HarmonyOS, logcat for Android, syslog for iOS). Useful for debugging app issues.", {
|
|
602
|
+
device: zod_1.z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
|
|
603
|
+
bundleName: zod_1.z.string().optional().describe("Filter logs by tag/process name"),
|
|
604
|
+
pid: zod_1.z.number().optional().describe("Filter logs by process ID"),
|
|
605
|
+
level: zod_1.z.string().optional().describe("Minimum log level: D/I/W/E/F for HarmonyOS/Android, Default/Info/Debug/Error/Fault for iOS"),
|
|
606
|
+
lines: zod_1.z.number().optional().describe("Number of recent log lines to retrieve (default: 200)"),
|
|
607
|
+
clear: zod_1.z.boolean().optional().describe("Clear log buffer before retrieving logs"),
|
|
608
|
+
}, { destructiveHint: false }, async ({ device, bundleName, pid, level, lines, clear }) => {
|
|
609
|
+
const robot = getRobotFromDevice(device);
|
|
610
|
+
const logs = await robot.getDeviceLogs({ bundleName, pid, level, lines, clear });
|
|
611
|
+
return logs;
|
|
612
|
+
});
|
|
613
|
+
return server;
|
|
614
|
+
};
|
|
615
|
+
exports.createMcpServer = createMcpServer;
|