-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathserver.ts
More file actions
656 lines (590 loc) · 21 KB
/
server.ts
File metadata and controls
656 lines (590 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import fs from "node:fs";
import os from "node:os";
import crypto from "node:crypto";
import { error, trace } from "./logger";
import { AndroidRobot, AndroidDeviceManager } from "./android";
import { ActionableError, Robot } from "./robot";
import { IosManager, IosRobot } from "./ios";
import { PNG } from "./png";
import { isScalingAvailable, Image } from "./image-utils";
import { Mobilecli } from "./mobilecli";
import { MobileDevice } from "./mobile-device";
interface MobilecliDevice {
id: string;
name: string;
platform: "android" | "ios";
type: "real" | "emulator" | "simulator";
version: string;
state: "online" | "offline";
}
interface MobilecliDevicesResponse {
devices: MobilecliDevice[];
}
export const getAgentVersion = (): string => {
const json = require("../package.json");
return json.version;
};
export const createMcpServer = (): McpServer => {
const server = new McpServer({
name: "mobile-mcp",
version: getAgentVersion(),
});
// an empty object to satisfy windsurf
const noParams = z.object({});
const getClientName = (): string => {
try {
const clientInfo = server.server.getClientVersion();
const clientName = clientInfo?.name || "unknown";
return clientName;
} catch (error: any) {
return "unknown";
}
};
type ZodSchemaShape = Record<string, z.ZodType>;
interface ToolAnnotations {
readOnlyHint?: boolean;
destructiveHint?: boolean;
}
const tool = (name: string, title: string, description: string, paramsSchema: ZodSchemaShape, annotations: ToolAnnotations, cb: (args: any) => Promise<string>) => {
server.registerTool(name, {
title,
description,
inputSchema: paramsSchema,
annotations,
}, (async (args: any, _extra: any) => {
try {
trace(`Invoking ${name} with args: ${JSON.stringify(args)}`);
const start = +new Date();
const response = await cb(args);
const duration = +new Date() - start;
trace(`=> ${response}`);
posthog("tool_invoked", { "ToolName": name, "Duration": duration }).then();
return {
content: [{ type: "text", text: response }],
};
} catch (error: any) {
posthog("tool_failed", { "ToolName": name }).then();
if (error instanceof ActionableError) {
return {
content: [{ type: "text", text: `${error.message}. Please fix the issue and try again.` }],
};
} else {
// a real exception
trace(`Tool '${description}' failed: ${error.message} stack: ${error.stack}`);
return {
content: [{ type: "text", text: `Error: ${error.message}` }],
isError: true,
};
}
}
}) as any);
};
const posthog = async (event: string, properties: Record<string, string | number>) => {
try {
const url = "https://us.i.posthog.com/i/v0/e/";
const api_key = "phc_KHRTZmkDsU7A8EbydEK8s4lJpPoTDyyBhSlwer694cS";
const name = os.hostname() + process.execPath;
const distinct_id = crypto.createHash("sha256").update(name).digest("hex");
const systemProps: any = {
Platform: os.platform(),
Product: "mobile-mcp",
Version: getAgentVersion(),
NodeVersion: process.version,
};
const clientName = getClientName();
if (clientName !== "unknown") {
systemProps.AgentName = clientName;
}
await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
api_key,
event,
properties: {
...systemProps,
...properties,
},
distinct_id,
})
});
} catch (err: any) {
// ignore
}
};
const mobilecli = new Mobilecli();
posthog("launch", {}).then();
const ensureMobilecliAvailable = (): void => {
try {
const version = mobilecli.getVersion();
if (version.startsWith("failed")) {
throw new Error("mobilecli version check failed");
}
} catch (error: any) {
throw new 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`);
}
};
const getRobotFromDevice = (deviceId: string): Robot => {
// from now on, we must have mobilecli working
ensureMobilecliAvailable();
// Check if it's an iOS device
const iosManager = new IosManager();
const iosDevices = iosManager.listDevices();
const iosDevice = iosDevices.find(d => d.deviceId === deviceId);
if (iosDevice) {
return new IosRobot(deviceId);
}
// Check if it's an Android device
const androidManager = new AndroidDeviceManager();
const androidDevices = androidManager.getConnectedDevices();
const androidDevice = androidDevices.find(d => d.deviceId === deviceId);
if (androidDevice) {
return new AndroidRobot(deviceId);
}
// Check if it's a simulator (will later replace all other device types as well)
const response = mobilecli.getDevices({
platform: "ios",
type: "simulator",
includeOffline: false,
});
if (response.status === "ok" && response.data && response.data.devices) {
for (const device of response.data.devices) {
if (device.id === deviceId) {
return new MobileDevice(deviceId);
}
}
}
throw new ActionableError(`Device "${deviceId}" not found. Use the mobile_list_available_devices tool to see available devices.`);
};
tool(
"mobile_list_available_devices",
"List Devices",
"List all available devices. This includes both physical devices and simulators. If there is more than one device returned, you need to let the user select one of them.",
{
noParams
},
{ readOnlyHint: true },
async ({}) => {
// from today onward, we must have mobilecli working
ensureMobilecliAvailable();
const iosManager = new IosManager();
const androidManager = new AndroidDeviceManager();
const devices: MobilecliDevice[] = [];
// Get Android devices with details
const androidDevices = androidManager.getConnectedDevicesWithDetails();
for (const device of androidDevices) {
devices.push({
id: device.deviceId,
name: device.name,
platform: "android",
type: "emulator",
version: device.version,
state: "online",
});
}
// Get iOS physical devices with details
try {
const iosDevices = iosManager.listDevicesWithDetails();
for (const device of iosDevices) {
devices.push({
id: device.deviceId,
name: device.deviceName,
platform: "ios",
type: "real",
version: device.version,
state: "online",
});
}
} catch (error: any) {
// If go-ios is not available, silently skip
}
// Get iOS simulators from mobilecli (excluding offline devices)
const response = mobilecli.getDevices({
platform: "ios",
type: "simulator",
includeOffline: false,
});
if (response.status === "ok" && response.data && response.data.devices) {
for (const device of response.data.devices) {
devices.push({
id: device.id,
name: device.name,
platform: device.platform,
type: device.type,
version: device.version,
state: "online",
});
}
}
const out: MobilecliDevicesResponse = { devices };
return JSON.stringify(out);
}
);
tool(
"mobile_list_apps",
"List Apps",
"List all the installed apps on the device",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
},
{ readOnlyHint: true },
async ({ device }) => {
const robot = getRobotFromDevice(device);
const result = await robot.listApps();
return `Found these apps on device: ${result.map(app => `${app.appName} (${app.packageName})`).join(", ")}`;
}
);
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.",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
packageName: z.string().describe("The package name of the app to launch"),
},
{ destructiveHint: true },
async ({ device, packageName }) => {
const robot = getRobotFromDevice(device);
await robot.launchApp(packageName);
return `Launched app ${packageName}`;
}
);
tool(
"mobile_terminate_app",
"Terminate App",
"Stop and terminate an app on mobile device",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
packageName: z.string().describe("The package name of the app to terminate"),
},
{ destructiveHint: true },
async ({ device, packageName }) => {
const robot = getRobotFromDevice(device);
await robot.terminateApp(packageName);
return `Terminated app ${packageName}`;
}
);
tool(
"mobile_install_app",
"Install App",
"Install an app on mobile device",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
path: 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"),
},
{ destructiveHint: true },
async ({ device, path }) => {
const robot = getRobotFromDevice(device);
await robot.installApp(path);
return `Installed app from ${path}`;
}
);
tool(
"mobile_uninstall_app",
"Uninstall App",
"Uninstall an app from mobile device",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
bundle_id: z.string().describe("Bundle identifier (iOS) or package name (Android) of the app to be uninstalled"),
},
{ destructiveHint: true },
async ({ device, bundle_id }) => {
const robot = getRobotFromDevice(device);
await robot.uninstallApp(bundle_id);
return `Uninstalled app ${bundle_id}`;
}
);
tool(
"mobile_get_screen_size",
"Get Screen Size",
"Get the screen size of the mobile device in pixels",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
},
{ readOnlyHint: true },
async ({ device }) => {
const robot = getRobotFromDevice(device);
const screenSize = await robot.getScreenSize();
return `Screen size is ${screenSize.width}x${screenSize.height} pixels`;
}
);
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.",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
x: z.number().describe("The x coordinate to click on the screen, in pixels"),
y: z.number().describe("The y coordinate to click on the screen, in pixels"),
},
{ destructiveHint: true },
async ({ device, x, y }) => {
const robot = getRobotFromDevice(device);
await robot.tap(x, y);
return `Clicked on screen at coordinates: ${x}, ${y}`;
}
);
tool(
"mobile_double_tap_on_screen",
"Double Tap Screen",
"Double-tap on the screen at given x,y coordinates.",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
x: z.number().describe("The x coordinate to double-tap, in pixels"),
y: z.number().describe("The y coordinate to double-tap, in pixels"),
},
{ destructiveHint: true },
async ({ device, x, y }) => {
const robot = getRobotFromDevice(device);
await robot!.doubleTap(x, y);
return `Double-tapped on screen at coordinates: ${x}, ${y}`;
}
);
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.",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
x: z.number().describe("The x coordinate to long press on the screen, in pixels"),
y: z.number().describe("The y coordinate to long press on the screen, in pixels"),
duration: z.number().min(1).max(10000).optional().describe("Duration of the long press in milliseconds. Defaults to 500ms."),
},
{ destructiveHint: true },
async ({ device, x, y, duration }) => {
const robot = getRobotFromDevice(device);
const pressDuration = duration ?? 500;
await robot.longPress(x, y, pressDuration);
return `Long pressed on screen at coordinates: ${x}, ${y} for ${pressDuration}ms`;
}
);
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.",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
},
{ readOnlyHint: true },
async ({ device }) => {
const robot = getRobotFromDevice(device);
const elements = await robot.getElementsOnScreen();
const result = elements.map(element => {
const out: any = {
type: element.type,
text: element.text,
label: element.label,
name: element.name,
value: element.value,
identifier: element.identifier,
coordinates: {
x: element.rect.x,
y: element.rect.y,
width: element.rect.width,
height: element.rect.height,
},
};
if (element.focused) {
out.focused = true;
}
return out;
});
return `Found these elements on screen: ${JSON.stringify(result)}`;
}
);
tool(
"mobile_press_button",
"Press Button",
"Press a button on device",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
button: 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)"),
},
{ destructiveHint: true },
async ({ device, button }) => {
const robot = getRobotFromDevice(device);
await robot.pressButton(button);
return `Pressed the button: ${button}`;
}
);
tool(
"mobile_open_url",
"Open URL",
"Open a URL in browser on device",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
url: z.string().describe("The URL to open"),
},
{ destructiveHint: true },
async ({ device, url }) => {
const robot = getRobotFromDevice(device);
await robot.openUrl(url);
return `Opened URL: ${url}`;
}
);
tool(
"mobile_swipe_on_screen",
"Swipe Screen",
"Swipe on the screen",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
direction: z.enum(["up", "down", "left", "right"]).describe("The direction to swipe"),
x: z.number().optional().describe("The x coordinate to start the swipe from, in pixels. If not provided, uses center of screen"),
y: z.number().optional().describe("The y coordinate to start the swipe from, in pixels. If not provided, uses center of screen"),
distance: z.number().optional().describe("The distance to swipe in pixels. Defaults to 400 pixels for iOS or 30% of screen dimension for Android"),
},
{ destructiveHint: true },
async ({ device, direction, x, y, distance }) => {
const robot = getRobotFromDevice(device);
if (x !== undefined && y !== undefined) {
// Use coordinate-based swipe
await robot.swipeFromCoordinate(x, y, direction, distance);
const distanceText = distance ? ` ${distance} pixels` : "";
return `Swiped ${direction}${distanceText} from coordinates: ${x}, ${y}`;
} else {
// Use center-based swipe
await robot.swipe(direction);
return `Swiped ${direction} on screen`;
}
}
);
tool(
"mobile_type_keys",
"Type Text",
"Type text into the focused element",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
text: z.string().describe("The text to type"),
submit: z.boolean().describe("Whether to submit the text. If true, the text will be submitted as if the user pressed the enter key."),
},
{ destructiveHint: true },
async ({ device, text, submit }) => {
const robot = getRobotFromDevice(device);
await robot.sendKeys(text);
if (submit) {
await robot.pressButton("ENTER");
}
return `Typed text: ${text}`;
}
);
tool(
"mobile_save_screenshot",
"Save Screenshot",
"Save a screenshot of the mobile device to a file",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
saveTo: z.string().describe("The path to save the screenshot to"),
},
{ destructiveHint: true },
async ({ device, saveTo }) => {
const robot = getRobotFromDevice(device);
const screenshot = await robot.getScreenshot();
fs.writeFileSync(saveTo, screenshot);
return `Screenshot saved to: ${saveTo}`;
}
);
server.registerTool(
"mobile_take_screenshot",
{
title: "Take Screenshot",
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.",
inputSchema: {
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
},
annotations: {
readOnlyHint: true,
},
},
async ({ device }) => {
try {
const robot = getRobotFromDevice(device);
const screenSize = await robot.getScreenSize();
let screenshot = await robot.getScreenshot();
let mimeType = "image/png";
// validate we received a png, will throw exception otherwise
const image = new PNG(screenshot);
const pngSize = image.getDimensions();
if (pngSize.width <= 0 || pngSize.height <= 0) {
throw new ActionableError("Screenshot is invalid. Please try again.");
}
if (isScalingAvailable()) {
trace("Image scaling is available, resizing screenshot");
const image = Image.fromBuffer(screenshot);
const beforeSize = screenshot.length;
screenshot = image.resize(Math.floor(pngSize.width / screenSize.scale))
.jpeg({ quality: 75 })
.toBuffer();
const afterSize = screenshot.length;
trace(`Screenshot resized from ${beforeSize} bytes to ${afterSize} bytes`);
mimeType = "image/jpeg";
}
const screenshot64 = screenshot.toString("base64");
trace(`Screenshot taken: ${screenshot.length} bytes`);
posthog("tool_invoked", {
"ToolName": "mobile_take_screenshot",
"ScreenshotFilesize": screenshot64.length,
"ScreenshotMimeType": mimeType,
"ScreenshotWidth": pngSize.width,
"ScreenshotHeight": pngSize.height,
}).then();
return {
content: [{ type: "image", data: screenshot64, mimeType }]
};
} catch (err: any) {
error(`Error taking screenshot: ${err.message} ${err.stack}`);
return {
content: [{ type: "text", text: `Error: ${err.message}` }],
isError: true,
};
}
}
);
tool(
"mobile_set_orientation",
"Set Orientation",
"Change the screen orientation of the device",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you."),
orientation: z.enum(["portrait", "landscape"]).describe("The desired orientation"),
},
{ destructiveHint: true },
async ({ device, orientation }) => {
const robot = getRobotFromDevice(device);
await robot.setOrientation(orientation);
return `Changed device orientation to ${orientation}`;
}
);
tool(
"mobile_get_orientation",
"Get Orientation",
"Get the current screen orientation of the device",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
},
{ readOnlyHint: true },
async ({ device }) => {
const robot = getRobotFromDevice(device);
const orientation = await robot.getOrientation();
return `Current device orientation is ${orientation}`;
}
);
tool(
"mobile_get_current_activity",
"Get Current Activity",
"Get the currently running activity (Android) or foreground app (iOS). Returns the package name for Android or bundle ID for iOS.",
{
device: z.string().describe("The device identifier to use. Use mobile_list_available_devices to find which devices are available to you.")
},
{ readOnlyHint: true },
async ({ device }) => {
const robot = getRobotFromDevice(device);
const activity = await robot.getCurrentActivity();
return JSON.stringify(activity);
}
);
return server;
};