@browserstack/mcp-server 1.0.12 → 1.0.14

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 (52) hide show
  1. package/README.md +22 -0
  2. package/dist/config.js +2 -6
  3. package/dist/index.js +31 -30
  4. package/dist/lib/api.js +3 -57
  5. package/dist/lib/constants.js +14 -0
  6. package/dist/lib/device-cache.js +32 -33
  7. package/dist/lib/error.js +3 -6
  8. package/dist/lib/fuzzy.js +1 -4
  9. package/dist/lib/inmemory-store.js +1 -0
  10. package/dist/lib/instrumentation.js +12 -18
  11. package/dist/lib/local.js +27 -35
  12. package/dist/lib/utils.js +29 -4
  13. package/dist/logger.js +4 -9
  14. package/dist/tools/accessibility.js +9 -12
  15. package/dist/tools/accessiblity-utils/accessibility.js +14 -22
  16. package/dist/tools/appautomate-utils/appautomate.js +95 -0
  17. package/dist/tools/appautomate.js +116 -0
  18. package/dist/tools/applive-utils/fuzzy-search.js +3 -6
  19. package/dist/tools/applive-utils/start-session.js +14 -20
  20. package/dist/tools/applive-utils/upload-app.js +12 -51
  21. package/dist/tools/applive.js +18 -25
  22. package/dist/tools/automate-utils/fetch-screenshots.js +59 -0
  23. package/dist/tools/automate.js +44 -37
  24. package/dist/tools/bstack-sdk.js +14 -18
  25. package/dist/tools/failurelogs-utils/app-automate.js +88 -0
  26. package/dist/tools/failurelogs-utils/automate.js +97 -0
  27. package/dist/tools/getFailureLogs.js +173 -0
  28. package/dist/tools/live-utils/desktop-filter.js +8 -11
  29. package/dist/tools/live-utils/mobile-filter.js +7 -10
  30. package/dist/tools/live-utils/start-session.js +17 -23
  31. package/dist/tools/live-utils/types.js +2 -5
  32. package/dist/tools/live-utils/version-resolver.js +1 -4
  33. package/dist/tools/live.js +23 -29
  34. package/dist/tools/observability.js +12 -19
  35. package/dist/tools/sdk-utils/constants.js +3 -9
  36. package/dist/tools/sdk-utils/instructions.js +4 -9
  37. package/dist/tools/sdk-utils/types.js +1 -2
  38. package/dist/tools/testmanagement-utils/TCG-utils/api.js +259 -0
  39. package/dist/tools/testmanagement-utils/TCG-utils/config.js +5 -0
  40. package/dist/tools/testmanagement-utils/TCG-utils/helpers.js +53 -0
  41. package/dist/tools/testmanagement-utils/TCG-utils/types.js +8 -0
  42. package/dist/tools/testmanagement-utils/add-test-result.js +61 -0
  43. package/dist/tools/testmanagement-utils/create-project-folder.js +21 -28
  44. package/dist/tools/testmanagement-utils/create-testcase.js +30 -38
  45. package/dist/tools/testmanagement-utils/create-testrun.js +23 -30
  46. package/dist/tools/testmanagement-utils/list-testcases.js +16 -23
  47. package/dist/tools/testmanagement-utils/list-testruns.js +13 -20
  48. package/dist/tools/testmanagement-utils/testcase-from-file.js +42 -0
  49. package/dist/tools/testmanagement-utils/update-testrun.js +16 -23
  50. package/dist/tools/testmanagement-utils/upload-file.js +101 -0
  51. package/dist/tools/testmanagement.js +115 -46
  52. package/package.json +10 -6
@@ -1,24 +1,16 @@
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.startAccessibilityScan = startAccessibilityScan;
7
- exports.pollScanStatus = pollScanStatus;
8
- exports.waitUntilScanComplete = waitUntilScanComplete;
9
- const axios_1 = __importDefault(require("axios"));
10
- const config_js_1 = __importDefault(require("../../config.js"));
11
- const axios_2 = require("axios");
12
- async function startAccessibilityScan(name, urlList) {
1
+ import axios from "axios";
2
+ import config from "../../config.js";
3
+ import { AxiosError } from "axios";
4
+ export async function startAccessibilityScan(name, urlList) {
13
5
  try {
14
- const response = await axios_1.default.post("https://api-accessibility.browserstack.com/api/website-scanner/v1/scans", {
6
+ const response = await axios.post("https://api-accessibility.browserstack.com/api/website-scanner/v1/scans", {
15
7
  name,
16
8
  urlList,
17
9
  recurring: false,
18
10
  }, {
19
11
  auth: {
20
- username: config_js_1.default.browserstackUsername,
21
- password: config_js_1.default.browserstackAccessKey,
12
+ username: config.browserstackUsername,
13
+ password: config.browserstackAccessKey,
22
14
  },
23
15
  });
24
16
  if (!response.data.success) {
@@ -27,7 +19,7 @@ async function startAccessibilityScan(name, urlList) {
27
19
  return response.data;
28
20
  }
29
21
  catch (error) {
30
- if (error instanceof axios_2.AxiosError) {
22
+ if (error instanceof AxiosError) {
31
23
  if (error.response?.data?.error) {
32
24
  throw new Error(`Failed to start accessibility scan: ${error.response?.data?.error}`);
33
25
  }
@@ -38,12 +30,12 @@ async function startAccessibilityScan(name, urlList) {
38
30
  throw error;
39
31
  }
40
32
  }
41
- async function pollScanStatus(scanId, scanRunId) {
33
+ export async function pollScanStatus(scanId, scanRunId) {
42
34
  try {
43
- const response = await axios_1.default.get(`https://api-accessibility.browserstack.com/api/website-scanner/v1/scans/${scanId}/scan_runs/${scanRunId}/status`, {
35
+ const response = await axios.get(`https://api-accessibility.browserstack.com/api/website-scanner/v1/scans/${scanId}/scan_runs/${scanRunId}/status`, {
44
36
  auth: {
45
- username: config_js_1.default.browserstackUsername,
46
- password: config_js_1.default.browserstackAccessKey,
37
+ username: config.browserstackUsername,
38
+ password: config.browserstackAccessKey,
47
39
  },
48
40
  });
49
41
  if (!response.data.success) {
@@ -52,13 +44,13 @@ async function pollScanStatus(scanId, scanRunId) {
52
44
  return response.data.data?.status || "unknown";
53
45
  }
54
46
  catch (error) {
55
- if (error instanceof axios_2.AxiosError) {
47
+ if (error instanceof AxiosError) {
56
48
  throw new Error(`Failed to get scan status: ${error.response?.data?.message || error.message}`);
57
49
  }
58
50
  throw error;
59
51
  }
60
52
  }
61
- async function waitUntilScanComplete(scanId, scanRunId) {
53
+ export async function waitUntilScanComplete(scanId, scanRunId) {
62
54
  return new Promise((resolve, reject) => {
63
55
  const interval = setInterval(async () => {
64
56
  try {
@@ -0,0 +1,95 @@
1
+ import fs from "fs";
2
+ import axios from "axios";
3
+ import config from "../../config.js";
4
+ import FormData from "form-data";
5
+ import { customFuzzySearch } from "../../lib/fuzzy.js";
6
+ /**
7
+ * Finds devices that exactly match the provided display name.
8
+ * Uses fuzzy search first, and then filters for exact case-insensitive match.
9
+ */
10
+ export function findMatchingDevice(devices, deviceName) {
11
+ const matches = customFuzzySearch(devices, ["display_name"], deviceName, 5);
12
+ if (matches.length === 0) {
13
+ const availableDevices = [
14
+ ...new Set(devices.map((d) => d.display_name)),
15
+ ].join(", ");
16
+ throw new Error(`No devices found matching "${deviceName}". Available devices: ${availableDevices}`);
17
+ }
18
+ const exactMatches = matches.filter((m) => m.display_name.toLowerCase() === deviceName.toLowerCase());
19
+ if (exactMatches.length === 0) {
20
+ const suggestions = [...new Set(matches.map((d) => d.display_name))].join(", ");
21
+ throw new Error(`Alternative devices found: ${suggestions}. Please select one of these exact device names.`);
22
+ }
23
+ return exactMatches;
24
+ }
25
+ /**
26
+ * Extracts all unique OS versions from a device list and sorts them.
27
+ */
28
+ export function getDeviceVersions(devices) {
29
+ return [...new Set(devices.map((d) => d.os_version))].sort();
30
+ }
31
+ /**
32
+ * Resolves the requested platform version against available versions.
33
+ * Supports 'latest' and 'oldest' as dynamic selectors.
34
+ */
35
+ export function resolveVersion(versions, requestedVersion) {
36
+ if (requestedVersion === "latest") {
37
+ return versions[versions.length - 1];
38
+ }
39
+ if (requestedVersion === "oldest") {
40
+ return versions[0];
41
+ }
42
+ const match = versions.find((v) => v === requestedVersion);
43
+ if (!match) {
44
+ throw new Error(`Version "${requestedVersion}" not found. Available versions: ${versions.join(", ")}`);
45
+ }
46
+ return match;
47
+ }
48
+ /**
49
+ * Validates the input arguments for taking app screenshots.
50
+ * Checks for presence and correctness of platform, device, and file types.
51
+ */
52
+ export function validateArgs(args) {
53
+ const { desiredPlatform, desiredPlatformVersion, appPath, desiredPhone } = args;
54
+ if (!desiredPlatform || !desiredPhone) {
55
+ throw new Error("Missing required arguments: desiredPlatform and desiredPhone are required");
56
+ }
57
+ if (!desiredPlatformVersion) {
58
+ throw new Error("Missing required arguments: desiredPlatformVersion is required");
59
+ }
60
+ if (!appPath) {
61
+ throw new Error("You must provide an appPath.");
62
+ }
63
+ if (desiredPlatform === "android" && !appPath.endsWith(".apk")) {
64
+ throw new Error("You must provide a valid Android app path (.apk).");
65
+ }
66
+ if (desiredPlatform === "ios" && !appPath.endsWith(".ipa")) {
67
+ throw new Error("You must provide a valid iOS app path (.ipa).");
68
+ }
69
+ }
70
+ /**
71
+ * Uploads an application file to AppAutomate and returns the app URL
72
+ */
73
+ export async function uploadApp(appPath) {
74
+ const filePath = appPath;
75
+ if (!fs.existsSync(filePath)) {
76
+ throw new Error(`File not found at path: ${filePath}`);
77
+ }
78
+ const formData = new FormData();
79
+ formData.append("file", fs.createReadStream(filePath));
80
+ const response = await axios.post("https://api-cloud.browserstack.com/app-automate/upload", formData, {
81
+ headers: {
82
+ ...formData.getHeaders(),
83
+ },
84
+ auth: {
85
+ username: config.browserstackUsername,
86
+ password: config.browserstackAccessKey,
87
+ },
88
+ });
89
+ if (response.data.app_url) {
90
+ return response.data.app_url;
91
+ }
92
+ else {
93
+ throw new Error(`Failed to upload app: ${response.data}`);
94
+ }
95
+ }
@@ -0,0 +1,116 @@
1
+ import { z } from "zod";
2
+ import logger from "../logger.js";
3
+ import config from "../config.js";
4
+ import { trackMCP } from "../lib/instrumentation.js";
5
+ import { maybeCompressBase64 } from "../lib/utils.js";
6
+ import { remote } from "webdriverio";
7
+ import { getDevicesAndBrowsers, BrowserStackProducts, } from "../lib/device-cache.js";
8
+ import { findMatchingDevice, getDeviceVersions, resolveVersion, validateArgs, uploadApp, } from "./appautomate-utils/appautomate.js";
9
+ var Platform;
10
+ (function (Platform) {
11
+ Platform["ANDROID"] = "android";
12
+ Platform["IOS"] = "ios";
13
+ })(Platform || (Platform = {}));
14
+ /**
15
+ * Launches an app on a selected BrowserStack device and takes a screenshot.
16
+ */
17
+ async function takeAppScreenshot(args) {
18
+ let driver;
19
+ try {
20
+ validateArgs(args);
21
+ const { desiredPlatform, desiredPhone, appPath } = args;
22
+ let { desiredPlatformVersion } = args;
23
+ const platforms = (await getDevicesAndBrowsers(BrowserStackProducts.APP_AUTOMATE)).mobile;
24
+ const platformData = platforms.find((p) => p.os === desiredPlatform.toLowerCase());
25
+ if (!platformData) {
26
+ throw new Error(`Platform ${desiredPlatform} not found in device cache.`);
27
+ }
28
+ const matchingDevices = findMatchingDevice(platformData.devices, desiredPhone);
29
+ const availableVersions = getDeviceVersions(matchingDevices);
30
+ desiredPlatformVersion = resolveVersion(availableVersions, desiredPlatformVersion);
31
+ const selectedDevice = matchingDevices.find((d) => d.os_version === desiredPlatformVersion);
32
+ if (!selectedDevice) {
33
+ throw new Error(`Device "${desiredPhone}" with version ${desiredPlatformVersion} not found.`);
34
+ }
35
+ const app_url = await uploadApp(appPath);
36
+ logger.info(`App uploaded. URL: ${app_url}`);
37
+ const capabilities = {
38
+ platformName: desiredPlatform,
39
+ "appium:platformVersion": selectedDevice.os_version,
40
+ "appium:deviceName": selectedDevice.device,
41
+ "appium:app": app_url,
42
+ "appium:autoGrantPermissions": true,
43
+ "bstack:options": {
44
+ userName: config.browserstackUsername,
45
+ accessKey: config.browserstackAccessKey,
46
+ appiumVersion: "2.0.1",
47
+ },
48
+ };
49
+ logger.info("Starting WebDriver session on BrowserStack...");
50
+ driver = await remote({
51
+ protocol: "https",
52
+ hostname: "hub.browserstack.com",
53
+ port: 443,
54
+ path: "/wd/hub",
55
+ capabilities,
56
+ });
57
+ const screenshotBase64 = await driver.takeScreenshot();
58
+ const compressed = await maybeCompressBase64(screenshotBase64);
59
+ return {
60
+ content: [
61
+ {
62
+ type: "image",
63
+ data: compressed,
64
+ mimeType: "image/png",
65
+ name: `screenshot-${selectedDevice.device}-${Date.now()}`,
66
+ },
67
+ ],
68
+ };
69
+ }
70
+ catch (error) {
71
+ logger.error("Error during app automation or screenshot capture", error);
72
+ throw error;
73
+ }
74
+ finally {
75
+ if (driver) {
76
+ logger.info("Cleaning up WebDriver session...");
77
+ await driver.deleteSession();
78
+ }
79
+ }
80
+ }
81
+ /**
82
+ * Registers the `takeAppScreenshot` tool with the MCP server.
83
+ */
84
+ export default function addAppAutomationTools(server) {
85
+ server.tool("takeAppScreenshot", "Use this tool to take a screenshot of an app running on a BrowserStack device. This is useful for visual testing and debugging.", {
86
+ desiredPhone: z
87
+ .string()
88
+ .describe("The full name of the device to run the app on. Example: 'iPhone 12 Pro' or 'Samsung Galaxy S20'. Always ask the user for the device they want to use."),
89
+ desiredPlatformVersion: z
90
+ .string()
91
+ .describe("The platform version to run the app on. Use 'latest' or 'oldest' for dynamic resolution."),
92
+ desiredPlatform: z
93
+ .enum([Platform.ANDROID, Platform.IOS])
94
+ .describe("Platform to run the app on. Either 'android' or 'ios'."),
95
+ appPath: z
96
+ .string()
97
+ .describe("The path to the .apk or .ipa file. Required for app installation."),
98
+ }, async (args) => {
99
+ try {
100
+ trackMCP("takeAppScreenshot", server.server.getClientVersion());
101
+ return await takeAppScreenshot(args);
102
+ }
103
+ catch (error) {
104
+ trackMCP("takeAppScreenshot", server.server.getClientVersion(), error);
105
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
106
+ return {
107
+ content: [
108
+ {
109
+ type: "text",
110
+ text: `Error during app automation or screenshot capture: ${errorMessage}`,
111
+ },
112
+ ],
113
+ };
114
+ }
115
+ });
116
+ }
@@ -1,11 +1,8 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fuzzySearchDevices = fuzzySearchDevices;
4
- const fuzzy_1 = require("../../lib/fuzzy");
1
+ import { customFuzzySearch } from "../../lib/fuzzy.js";
5
2
  /**
6
3
  * Fuzzy searches App Live device entries by name.
7
4
  */
8
- async function fuzzySearchDevices(devices, query, limit = 5) {
9
- const top_match = (0, fuzzy_1.customFuzzySearch)(devices, ["device", "display_name"], query, limit);
5
+ export async function fuzzySearchDevices(devices, query, limit = 5) {
6
+ const top_match = customFuzzySearch(devices, ["device", "display_name"], query, limit);
10
7
  return top_match;
11
8
  }
@@ -1,31 +1,25 @@
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.startSession = startSession;
7
- const child_process_1 = __importDefault(require("child_process"));
8
- const logger_1 = __importDefault(require("../../logger"));
9
- const device_cache_1 = require("../../lib/device-cache");
10
- const fuzzy_search_1 = require("./fuzzy-search");
11
- const utils_1 = require("../../lib/utils");
12
- const upload_app_1 = require("./upload-app");
1
+ import childProcess from "child_process";
2
+ import logger from "../../logger.js";
3
+ import { BrowserStackProducts, getDevicesAndBrowsers, } from "../../lib/device-cache.js";
4
+ import { fuzzySearchDevices } from "./fuzzy-search.js";
5
+ import { sanitizeUrlParam } from "../../lib/utils.js";
6
+ import { uploadApp } from "./upload-app.js";
13
7
  /**
14
8
  * Starts an App Live session after filtering, fuzzy matching, and launching.
15
9
  * @param args - The arguments for starting the session.
16
10
  * @returns The launch URL for the session.
17
11
  * @throws Will throw an error if no devices are found or if the app URL is invalid.
18
12
  */
19
- async function startSession(args) {
13
+ export async function startSession(args) {
20
14
  const { appPath, desiredPlatform, desiredPhone } = args;
21
15
  let { desiredPlatformVersion } = args;
22
- const data = await (0, device_cache_1.getDevicesAndBrowsers)("app_live");
16
+ const data = await getDevicesAndBrowsers(BrowserStackProducts.APP_LIVE);
23
17
  const allDevices = data.mobile.flatMap((group) => group.devices.map((dev) => ({ ...dev, os: group.os })));
24
18
  desiredPlatformVersion = resolvePlatformVersion(allDevices, desiredPlatform, desiredPlatformVersion);
25
19
  const filteredDevices = filterDevicesByPlatformAndVersion(allDevices, desiredPlatform, desiredPlatformVersion);
26
- const matches = await (0, fuzzy_search_1.fuzzySearchDevices)(filteredDevices, desiredPhone);
20
+ const matches = await fuzzySearchDevices(filteredDevices, desiredPhone);
27
21
  const selectedDevice = validateAndSelectDevice(matches, desiredPhone, desiredPlatform, desiredPlatformVersion);
28
- const { app_url } = await (0, upload_app_1.uploadApp)(appPath);
22
+ const { app_url } = await uploadApp(appPath);
29
23
  validateAppUrl(app_url);
30
24
  const launchUrl = constructLaunchUrl(app_url, selectedDevice, desiredPlatform, desiredPlatformVersion);
31
25
  openBrowser(launchUrl);
@@ -120,7 +114,7 @@ function validateAppUrl(appUrl) {
120
114
  * @returns The constructed launch URL.
121
115
  */
122
116
  function constructLaunchUrl(appUrl, device, desiredPlatform, desiredPlatformVersion) {
123
- const deviceParam = (0, utils_1.sanitizeUrlParam)(device.display_name.replace(/\s+/g, "+"));
117
+ const deviceParam = sanitizeUrlParam(device.display_name.replace(/\s+/g, "+"));
124
118
  const params = new URLSearchParams({
125
119
  os: desiredPlatform,
126
120
  os_version: desiredPlatformVersion,
@@ -144,16 +138,16 @@ function openBrowser(launchUrl) {
144
138
  ? ["cmd", "/c", "start", launchUrl]
145
139
  : ["xdg-open", launchUrl];
146
140
  // nosemgrep:javascript.lang.security.detect-child-process.detect-child-process
147
- const child = child_process_1.default.spawn(command[0], command.slice(1), {
141
+ const child = childProcess.spawn(command[0], command.slice(1), {
148
142
  stdio: "ignore",
149
143
  detached: true,
150
144
  });
151
145
  child.on("error", (error) => {
152
- logger_1.default.error(`Failed to open browser automatically: ${error}. Please open this URL manually: ${launchUrl}`);
146
+ logger.error(`Failed to open browser automatically: ${error}. Please open this URL manually: ${launchUrl}`);
153
147
  });
154
148
  child.unref();
155
149
  }
156
150
  catch (error) {
157
- logger_1.default.error(`Failed to open browser automatically: ${error}. Please open this URL manually: ${launchUrl}`);
151
+ logger.error(`Failed to open browser automatically: ${error}. Please open this URL manually: ${launchUrl}`);
158
152
  }
159
153
  }
@@ -1,66 +1,27 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.uploadApp = uploadApp;
40
- const axios_1 = __importStar(require("axios"));
41
- const form_data_1 = __importDefault(require("form-data"));
42
- const fs_1 = __importDefault(require("fs"));
43
- const config_1 = __importDefault(require("../../config"));
44
- async function uploadApp(filePath) {
45
- if (!fs_1.default.existsSync(filePath)) {
1
+ import axios, { AxiosError } from "axios";
2
+ import FormData from "form-data";
3
+ import fs from "fs";
4
+ import config from "../../config.js";
5
+ export async function uploadApp(filePath) {
6
+ if (!fs.existsSync(filePath)) {
46
7
  throw new Error(`File not found at path: ${filePath}`);
47
8
  }
48
- const formData = new form_data_1.default();
49
- formData.append("file", fs_1.default.createReadStream(filePath));
9
+ const formData = new FormData();
10
+ formData.append("file", fs.createReadStream(filePath));
50
11
  try {
51
- const response = await axios_1.default.post("https://api-cloud.browserstack.com/app-live/upload", formData, {
12
+ const response = await axios.post("https://api-cloud.browserstack.com/app-live/upload", formData, {
52
13
  headers: {
53
14
  ...formData.getHeaders(),
54
15
  },
55
16
  auth: {
56
- username: config_1.default.browserstackUsername,
57
- password: config_1.default.browserstackAccessKey,
17
+ username: config.browserstackUsername,
18
+ password: config.browserstackAccessKey,
58
19
  },
59
20
  });
60
21
  return response.data;
61
22
  }
62
23
  catch (error) {
63
- if (error instanceof axios_1.AxiosError) {
24
+ if (error instanceof AxiosError) {
64
25
  throw new Error(`Failed to upload app: ${error.response?.data?.message || error.message}`);
65
26
  }
66
27
  throw error;
@@ -1,19 +1,12 @@
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.startAppLiveSession = startAppLiveSession;
7
- exports.default = addAppLiveTools;
8
- const zod_1 = require("zod");
9
- const fs_1 = __importDefault(require("fs"));
10
- const start_session_1 = require("./applive-utils/start-session");
11
- const logger_1 = __importDefault(require("../logger"));
12
- const instrumentation_1 = require("../lib/instrumentation");
1
+ import { z } from "zod";
2
+ import fs from "fs";
3
+ import { startSession } from "./applive-utils/start-session.js";
4
+ import logger from "../logger.js";
5
+ import { trackMCP } from "../lib/instrumentation.js";
13
6
  /**
14
7
  * Launches an App Live Session on BrowserStack.
15
8
  */
16
- async function startAppLiveSession(args) {
9
+ export async function startAppLiveSession(args) {
17
10
  if (!args.desiredPlatform) {
18
11
  throw new Error("You must provide a desiredPlatform.");
19
12
  }
@@ -31,16 +24,16 @@ async function startAppLiveSession(args) {
31
24
  }
32
25
  // check if the app path exists && is readable
33
26
  try {
34
- if (!fs_1.default.existsSync(args.appPath)) {
27
+ if (!fs.existsSync(args.appPath)) {
35
28
  throw new Error("The app path does not exist.");
36
29
  }
37
- fs_1.default.accessSync(args.appPath, fs_1.default.constants.R_OK);
30
+ fs.accessSync(args.appPath, fs.constants.R_OK);
38
31
  }
39
32
  catch (error) {
40
- logger_1.default.error("The app path does not exist or is not readable: %s", error);
33
+ logger.error("The app path does not exist or is not readable: %s", error);
41
34
  throw new Error("The app path does not exist or is not readable.");
42
35
  }
43
- const launchUrl = await (0, start_session_1.startSession)({
36
+ const launchUrl = await startSession({
44
37
  appPath: args.appPath,
45
38
  desiredPlatform: args.desiredPlatform,
46
39
  desiredPhone: args.desiredPhone,
@@ -55,28 +48,28 @@ async function startAppLiveSession(args) {
55
48
  ],
56
49
  };
57
50
  }
58
- function addAppLiveTools(server) {
51
+ export default function addAppLiveTools(server) {
59
52
  server.tool("runAppLiveSession", "Use this tool when user wants to manually check their app on a particular mobile device using BrowserStack's cloud infrastructure. Can be used to debug crashes, slow performance, etc.", {
60
- desiredPhone: zod_1.z
53
+ desiredPhone: z
61
54
  .string()
62
55
  .describe("The full name of the device to run the app on. Example: 'iPhone 12 Pro' or 'Samsung Galaxy S20' or 'Google Pixel 6'. Always ask the user for the device they want to use, do not assume it. "),
63
- desiredPlatformVersion: zod_1.z
56
+ desiredPlatformVersion: z
64
57
  .string()
65
58
  .describe("Specifies the platform version to run the app on. For example, use '12.0' for Android or '16.0' for iOS. If the user says 'latest', 'newest', or similar, normalize it to 'latest'. Likewise, convert terms like 'earliest' or 'oldest' to 'oldest'."),
66
- desiredPlatform: zod_1.z
59
+ desiredPlatform: z
67
60
  .enum(["android", "ios"])
68
61
  .describe("Which platform to run on, examples: 'android', 'ios'. Set this based on the app path provided."),
69
- appPath: zod_1.z
62
+ appPath: z
70
63
  .string()
71
64
  .describe("The path to the .ipa or .apk file to install on the device. Always ask the user for the app path, do not assume it."),
72
65
  }, async (args) => {
73
66
  try {
74
- (0, instrumentation_1.trackMCP)("runAppLiveSession", server.server.getClientVersion());
67
+ trackMCP("runAppLiveSession", server.server.getClientVersion());
75
68
  return await startAppLiveSession(args);
76
69
  }
77
70
  catch (error) {
78
- logger_1.default.error("App live session failed: %s", error);
79
- (0, instrumentation_1.trackMCP)("runAppLiveSession", server.server.getClientVersion(), error);
71
+ logger.error("App live session failed: %s", error);
72
+ trackMCP("runAppLiveSession", server.server.getClientVersion(), error);
80
73
  return {
81
74
  content: [
82
75
  {
@@ -0,0 +1,59 @@
1
+ import config from "../../config.js";
2
+ import { assertOkResponse, maybeCompressBase64 } from "../../lib/utils.js";
3
+ import { SessionType } from "../../lib/constants.js";
4
+ //Extracts screenshot URLs from BrowserStack session logs
5
+ async function extractScreenshotUrls(sessionId, sessionType) {
6
+ const credentials = `${config.browserstackUsername}:${config.browserstackAccessKey}`;
7
+ const auth = Buffer.from(credentials).toString("base64");
8
+ const baseUrl = `https://api.browserstack.com/${sessionType === SessionType.Automate ? "automate" : "app-automate"}`;
9
+ const url = `${baseUrl}/sessions/${sessionId}/logs`;
10
+ const response = await fetch(url, {
11
+ headers: {
12
+ "Content-Type": "application/json",
13
+ Authorization: `Basic ${auth}`,
14
+ },
15
+ });
16
+ await assertOkResponse(response, "Session");
17
+ const text = await response.text();
18
+ const urls = [];
19
+ const SCREENSHOT_PATTERN = /REQUEST.*GET.*\/screenshot/;
20
+ const RESPONSE_VALUE_PATTERN = /"value"\s*:\s*"([^"]+)"/;
21
+ // Split logs into lines and process them
22
+ const lines = text.split("\n");
23
+ for (let i = 0; i < lines.length - 1; i++) {
24
+ const currentLine = lines[i];
25
+ const nextLine = lines[i + 1];
26
+ if (SCREENSHOT_PATTERN.test(currentLine)) {
27
+ const match = nextLine.match(RESPONSE_VALUE_PATTERN);
28
+ if (match && match[1]) {
29
+ urls.push(match[1]);
30
+ }
31
+ }
32
+ }
33
+ return urls;
34
+ }
35
+ //Converts screenshot URLs to base64 encoded images
36
+ async function convertUrlsToBase64(urls) {
37
+ const screenshots = await Promise.all(urls.map(async (url) => {
38
+ const response = await fetch(url);
39
+ const arrayBuffer = await response.arrayBuffer();
40
+ const base64 = Buffer.from(arrayBuffer).toString("base64");
41
+ // Compress the base64 image if needed
42
+ const compressedBase64 = await maybeCompressBase64(base64);
43
+ return {
44
+ url,
45
+ base64: compressedBase64,
46
+ };
47
+ }));
48
+ return screenshots;
49
+ }
50
+ //Fetches and converts screenshot URLs to base64 encoded images
51
+ export async function fetchAutomationScreenshots(sessionId, sessionType = SessionType.Automate) {
52
+ const urls = await extractScreenshotUrls(sessionId, sessionType);
53
+ if (urls.length === 0) {
54
+ return [];
55
+ }
56
+ // Take only the last 5 URLs
57
+ const lastFiveUrls = urls.slice(-5);
58
+ return await convertUrlsToBase64(lastFiveUrls);
59
+ }