@browserstack/mcp-server 1.4.0-beta.3 → 1.4.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 (38) hide show
  1. package/README.md +43 -29
  2. package/dist/lib/constants.d.ts +3 -0
  3. package/dist/lib/constants.js +3 -0
  4. package/dist/lib/untrusted-content.d.ts +15 -0
  5. package/dist/lib/untrusted-content.js +24 -0
  6. package/dist/lib/version-resolver.d.ts +0 -5
  7. package/dist/lib/version-resolver.js +8 -2
  8. package/dist/logger.js +1 -10
  9. package/dist/tools/accessibility.js +4 -3
  10. package/dist/tools/accessiblity-utils/accessibility-rag.js +3 -1
  11. package/dist/tools/automate-utils/list-session-ids.d.ts +28 -0
  12. package/dist/tools/automate-utils/list-session-ids.js +87 -0
  13. package/dist/tools/automate-utils/resolve-hashed-build-id.d.ts +30 -0
  14. package/dist/tools/automate-utils/resolve-hashed-build-id.js +124 -0
  15. package/dist/tools/automate.d.ts +7 -0
  16. package/dist/tools/automate.js +104 -1
  17. package/dist/tools/build-insights.js +40 -1
  18. package/dist/tools/failurelogs-utils/app-automate.js +4 -3
  19. package/dist/tools/failurelogs-utils/automate.js +5 -4
  20. package/dist/tools/failurelogs-utils/resolve-app-build-id.d.ts +2 -0
  21. package/dist/tools/failurelogs-utils/resolve-app-build-id.js +5 -0
  22. package/dist/tools/failurelogs-utils/video.d.ts +3 -0
  23. package/dist/tools/failurelogs-utils/video.js +25 -0
  24. package/dist/tools/get-failure-logs.js +28 -11
  25. package/dist/tools/observability.js +3 -1
  26. package/dist/tools/rca-agent-utils/format-rca.js +5 -4
  27. package/dist/tools/rca-agent-utils/get-failed-test-id.js +12 -0
  28. package/dist/tools/rca-agent-utils/types.d.ts +1 -0
  29. package/dist/tools/rca-agent.js +1 -1
  30. package/dist/tools/review-agent.js +2 -1
  31. package/dist/tools/sdk-utils/common/constants.d.ts +1 -1
  32. package/dist/tools/sdk-utils/common/constants.js +2 -1
  33. package/dist/tools/selfheal.js +1 -1
  34. package/dist/tools/testmanagement-utils/testcase-from-file.js +2 -1
  35. package/dist/tools/testmanagement-utils/upload-file.js +16 -2
  36. package/dist/tools/tool-handoff.d.ts +5 -1
  37. package/dist/tools/tool-handoff.js +7 -4
  38. package/package.json +1 -1
@@ -0,0 +1,124 @@
1
+ import { SessionType } from "../../lib/constants.js";
2
+ import { getBrowserStackAuth } from "../../lib/get-auth.js";
3
+ import { apiClient } from "../../lib/apiClient.js";
4
+ import logger from "../../logger.js";
5
+ import { getAutomationBaseUrl } from "../rca-agent-utils/constants.js";
6
+ import { extractTestIds } from "../rca-agent-utils/get-failed-test-id.js";
7
+ // Observability (Test Reporting & Analytics) build ids are usually UUIDs but
8
+ // some are 40-char hex, the same shape as Automate / App Automate "hashed ids".
9
+ // The two are never interchangeable, and the observability build API does not
10
+ // expose the hashed id. The deterministic bridge is any BrowserStack session that belongs to the
11
+ // build: the session detail endpoint reports its parent `build_hashed_id`.
12
+ const OBSERVABILITY_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ const HASHED_BUILD_ID_RE = /^[a-f0-9]{40}$/i;
14
+ // Only the first session id is needed; most builds surface one on page one.
15
+ const MAX_TEST_RUN_PAGES = 5;
16
+ export function isObservabilityBuildUuid(id) {
17
+ return OBSERVABILITY_UUID_RE.test(id.trim());
18
+ }
19
+ export function isHashedBuildId(id) {
20
+ return HASHED_BUILD_ID_RE.test(id.trim());
21
+ }
22
+ export function sessionDetailsUrl(sessionType, sessionId) {
23
+ const encoded = encodeURIComponent(sessionId);
24
+ switch (sessionType) {
25
+ case SessionType.Automate:
26
+ return `https://api.browserstack.com/automate/sessions/${encoded}.json`;
27
+ case SessionType.AppAutomate:
28
+ return `https://api.browserstack.com/app-automate/sessions/${encoded}.json`;
29
+ default: {
30
+ const _exhaustive = sessionType;
31
+ throw new Error(`Unsupported session type: ${_exhaustive}`);
32
+ }
33
+ }
34
+ }
35
+ /**
36
+ * Resolve the hashed build id that a session belongs to via the Automate /
37
+ * App Automate session detail endpoint. Returns undefined when the session
38
+ * cannot be fetched or does not report a build.
39
+ */
40
+ export async function resolveBuildIdFromSession(sessionId, sessionType, config) {
41
+ const authString = getBrowserStackAuth(config);
42
+ const auth = Buffer.from(authString).toString("base64");
43
+ const response = await apiClient.get({
44
+ url: sessionDetailsUrl(sessionType, sessionId),
45
+ headers: {
46
+ "Content-Type": "application/json",
47
+ Authorization: `Basic ${auth}`,
48
+ },
49
+ raise_error: false,
50
+ });
51
+ if (!response.ok) {
52
+ logger.warn(`Could not resolve build id for ${sessionType} session ${sessionId}: ${response.status}`);
53
+ return undefined;
54
+ }
55
+ const session = response.data?.automation_session;
56
+ const buildId = session?.build_hashed_id;
57
+ return typeof buildId === "string" && buildId.trim()
58
+ ? buildId.trim()
59
+ : undefined;
60
+ }
61
+ /**
62
+ * Find any BrowserStack session id attached to an observability build by
63
+ * walking its test runs. Returns undefined when no test reports a session
64
+ * (e.g. JUnit-uploaded builds that never ran on BrowserStack).
65
+ */
66
+ export async function findSessionIdForObservabilityBuild(observabilityBuildId, config) {
67
+ const authString = getBrowserStackAuth(config);
68
+ const auth = Buffer.from(authString).toString("base64");
69
+ const baseUrl = `${getAutomationBaseUrl()}/ext/v1/builds/${encodeURIComponent(observabilityBuildId)}/testRuns`;
70
+ let nextPage;
71
+ for (let page = 0; page < MAX_TEST_RUN_PAGES; page++) {
72
+ const response = await apiClient.get({
73
+ url: baseUrl,
74
+ headers: {
75
+ "Content-Type": "application/json",
76
+ Authorization: `Basic ${auth}`,
77
+ },
78
+ ...(nextPage ? { params: { next_page: nextPage } } : {}),
79
+ raise_error: false,
80
+ });
81
+ if (!response.ok) {
82
+ throw new Error(`Failed to fetch test runs for observability build "${observabilityBuildId}": ` +
83
+ `${response.status} ${response.statusText}`);
84
+ }
85
+ const data = response.data;
86
+ const withSession = extractTestIds(data?.hierarchy ?? []).find((test) => test.session_id);
87
+ if (withSession?.session_id) {
88
+ return withSession.session_id;
89
+ }
90
+ if (!data?.pagination?.has_next || !data.pagination.next_page) {
91
+ return undefined;
92
+ }
93
+ nextPage = data.pagination.next_page;
94
+ }
95
+ logger.warn(`resolveHashedBuildId: no session id in first ${MAX_TEST_RUN_PAGES} pages of build ${observabilityBuildId}`);
96
+ return undefined;
97
+ }
98
+ /**
99
+ * Convert an observability build UUID into the Automate / App Automate hashed
100
+ * build id in two deterministic API calls: pick any session of the build from
101
+ * its test runs, then read `build_hashed_id` from that session's details.
102
+ *
103
+ * When `sessionType` is omitted, Automate is tried first, then App Automate.
104
+ */
105
+ export async function resolveHashedBuildId(observabilityBuildId, config, sessionType) {
106
+ const buildId = observabilityBuildId.trim();
107
+ const sessionId = await findSessionIdForObservabilityBuild(buildId, config);
108
+ if (!sessionId) {
109
+ throw new Error(`No BrowserStack sessions found for observability build "${buildId}". ` +
110
+ "Only builds that ran on Automate or App Automate have sessions to list; " +
111
+ "uploaded-report builds (e.g. JUnit) do not.");
112
+ }
113
+ const candidates = sessionType
114
+ ? [sessionType]
115
+ : [SessionType.Automate, SessionType.AppAutomate];
116
+ for (const candidate of candidates) {
117
+ const hashedBuildId = await resolveBuildIdFromSession(sessionId, candidate, config);
118
+ if (hashedBuildId) {
119
+ return { hashedBuildId, sessionId, sessionType: candidate };
120
+ }
121
+ }
122
+ throw new Error(`Could not resolve the hashed build id for observability build "${buildId}" ` +
123
+ `from session "${sessionId}" (tried: ${candidates.join(", ")}).`);
124
+ }
@@ -6,4 +6,11 @@ export declare function fetchAutomationScreenshotsTool(args: {
6
6
  sessionId: string;
7
7
  sessionType: SessionType;
8
8
  }, config: BrowserStackConfig): Promise<CallToolResult>;
9
+ export declare function listSessionIdsTool(args: {
10
+ sessionType: SessionType;
11
+ buildId: string;
12
+ limit?: number;
13
+ offset?: number;
14
+ status?: string;
15
+ }, config: BrowserStackConfig): Promise<CallToolResult>;
9
16
  export default function addAutomationTools(server: McpServer, config: BrowserStackConfig): Record<string, any>;
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { fetchAutomationScreenshots } from "./automate-utils/fetch-screenshots.js";
3
+ import { DEFAULT_SESSION_LIST_LIMIT, listSessionIds, UnknownBuildError, } from "./automate-utils/list-session-ids.js";
4
+ import { isObservabilityBuildUuid, resolveHashedBuildId, } from "./automate-utils/resolve-hashed-build-id.js";
3
5
  import { SessionType } from "../lib/constants.js";
4
6
  import { trackMCP } from "../lib/instrumentation.js";
5
7
  import logger from "../logger.js";
@@ -48,10 +50,63 @@ export async function fetchAutomationScreenshotsTool(args, config) {
48
50
  };
49
51
  }
50
52
  }
53
+ export async function listSessionIdsTool(args, config) {
54
+ try {
55
+ // Accept the observability build id too. Observability ids are usually
56
+ // UUIDs but can also be 40-char hex like Automate hashed ids, so shape
57
+ // alone is not enough: try the REST list first and resolve on a miss.
58
+ const inputId = args.buildId.trim();
59
+ let buildId = inputId;
60
+ let resolvedNote;
61
+ const resolve = async () => {
62
+ const resolved = await resolveHashedBuildId(inputId, config, args.sessionType);
63
+ buildId = resolved.hashedBuildId;
64
+ resolvedNote = `Resolved observability build ${inputId} to hashed build id ${buildId}.`;
65
+ };
66
+ let sessions;
67
+ if (isObservabilityBuildUuid(inputId)) {
68
+ await resolve();
69
+ sessions = await listSessionIds({ ...args, buildId }, config);
70
+ }
71
+ else {
72
+ try {
73
+ sessions = await listSessionIds({ ...args, buildId }, config);
74
+ }
75
+ catch (error) {
76
+ if (!(error instanceof UnknownBuildError))
77
+ throw error;
78
+ try {
79
+ await resolve();
80
+ }
81
+ catch (resolveError) {
82
+ logger.debug("listSessions: id is neither a known hashed build nor a resolvable observability build", resolveError);
83
+ throw error;
84
+ }
85
+ sessions = await listSessionIds({ ...args, buildId }, config);
86
+ }
87
+ }
88
+ const content = [
89
+ {
90
+ type: "text",
91
+ text: sessions.length === 0
92
+ ? "No sessions found for this hashed build ID."
93
+ : JSON.stringify(sessions, null, 2),
94
+ },
95
+ ];
96
+ if (resolvedNote) {
97
+ content.push({ type: "text", text: resolvedNote });
98
+ }
99
+ return { content };
100
+ }
101
+ catch (error) {
102
+ logger.error("Error listing session IDs", error);
103
+ throw error;
104
+ }
105
+ }
51
106
  //Registers the fetchAutomationScreenshots tool with the MCP server
52
107
  export default function addAutomationTools(server, config) {
53
108
  const tools = {};
54
- tools.fetchAutomationScreenshots = server.tool("fetchAutomationScreenshots", "Fetch and process screenshots from a BrowserStack Automate session", {
109
+ tools.fetchAutomationScreenshots = server.tool("fetchAutomationScreenshots", "Fetch screenshots captured during an Automate/App Automate session.", {
55
110
  sessionId: z
56
111
  .string()
57
112
  .describe("The BrowserStack session ID to fetch screenshots from"),
@@ -83,5 +138,53 @@ export default function addAutomationTools(server, config) {
83
138
  };
84
139
  }
85
140
  });
141
+ tools.listSessions = server.tool("listSessions", "List sessions for a hashed Automate/App Automate build: session IDs, status, OS, browser/device, dashboard URL.", {
142
+ sessionType: z
143
+ .enum([SessionType.Automate, SessionType.AppAutomate])
144
+ .describe("Type of BrowserStack session"),
145
+ buildId: z
146
+ .string()
147
+ .describe("Hashed build id from the dashboard, or the observability build id from getBuildId."),
148
+ limit: z
149
+ .number()
150
+ .int()
151
+ .positive()
152
+ .optional()
153
+ .describe(`Max sessions to return. Defaults to ${DEFAULT_SESSION_LIST_LIMIT}.`),
154
+ offset: z
155
+ .number()
156
+ .int()
157
+ .min(0)
158
+ .optional()
159
+ .describe("Pagination offset for the REST session list."),
160
+ status: z
161
+ .string()
162
+ .optional()
163
+ .describe("Optional session status filter (e.g. done, running, error). Applied client-side."),
164
+ }, {
165
+ title: "List Sessions",
166
+ readOnlyHint: true,
167
+ openWorldHint: false,
168
+ destructiveHint: false,
169
+ idempotentHint: true,
170
+ }, async (args) => {
171
+ try {
172
+ trackMCP("listSessions", server.server.getClientVersion(), undefined, config);
173
+ return await listSessionIdsTool(args, config);
174
+ }
175
+ catch (error) {
176
+ trackMCP("listSessions", server.server.getClientVersion(), error, config);
177
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
178
+ return {
179
+ content: [
180
+ {
181
+ type: "text",
182
+ text: `Error listing session IDs: ${errorMessage}`,
183
+ },
184
+ ],
185
+ isError: true,
186
+ };
187
+ }
188
+ });
86
189
  return tools;
87
190
  }
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import logger from "../logger.js";
3
3
  import { fetchFromBrowserStackAPI, handleMCPError } from "../lib/utils.js";
4
4
  import { trackMCP } from "../lib/instrumentation.js";
5
+ import { resolveHashedBuildId } from "./automate-utils/resolve-hashed-build-id.js";
5
6
  // Tool function that fetches build insights from two APIs
6
7
  export async function fetchBuildInsightsTool(args, config) {
7
8
  try {
@@ -15,6 +16,7 @@ export async function fetchBuildInsightsTool(args, config) {
15
16
  return null;
16
17
  }),
17
18
  ]);
19
+ const { hashed_id, session_type } = await resolveInsightsHashedId(args.buildId, buildData, config);
18
20
  // Select useful fields for users
19
21
  const insights = {
20
22
  name: buildData.name,
@@ -33,6 +35,8 @@ export async function fetchBuildInsightsTool(args, config) {
33
35
  commit_sha: buildData.vcs_info?.sha,
34
36
  vcs_name: buildData.vcs_info?.name,
35
37
  quality_gate_result: qualityData?.quality_gate_result,
38
+ ...(hashed_id ? { hashed_id } : {}),
39
+ ...(session_type ? { session_type } : {}),
36
40
  };
37
41
  const qualityProfiles = qualityData?.quality_profiles?.map((profile) => ({
38
42
  name: profile.name,
@@ -56,10 +60,45 @@ export async function fetchBuildInsightsTool(args, config) {
56
60
  throw error;
57
61
  }
58
62
  }
63
+ /**
64
+ * The observability build payload does not carry the Automate hashed build id
65
+ * today. Prefer it if the API ever adds one; otherwise resolve it through any
66
+ * session of the build (two deterministic REST calls). Never blocks insights.
67
+ */
68
+ async function resolveInsightsHashedId(observabilityBuildId, buildData, config) {
69
+ const direct = extractHashedBuildId(buildData);
70
+ if (direct) {
71
+ return { hashed_id: direct };
72
+ }
73
+ try {
74
+ const resolved = await resolveHashedBuildId(observabilityBuildId, config);
75
+ return {
76
+ hashed_id: resolved.hashedBuildId,
77
+ session_type: resolved.sessionType,
78
+ };
79
+ }
80
+ catch (error) {
81
+ logger.warn("Could not resolve hashed build id for build insights", error);
82
+ return {};
83
+ }
84
+ }
85
+ function extractHashedBuildId(buildData) {
86
+ const candidates = [
87
+ buildData?.hashed_id,
88
+ buildData?.automate_hashed_id,
89
+ buildData?.hashedId,
90
+ ];
91
+ for (const candidate of candidates) {
92
+ if (typeof candidate === "string" &&
93
+ /^[a-z0-9]{40}$/i.test(candidate.trim()))
94
+ return candidate.trim();
95
+ }
96
+ return undefined;
97
+ }
59
98
  // Registers the fetchBuildInsights tool with the MCP server
60
99
  export default function addBuildInsightsTools(server, config) {
61
100
  const tools = {};
62
- tools.fetchBuildInsights = server.tool("fetchBuildInsights", "Fetches insights about a BrowserStack build by combining build details and quality gate results.", {
101
+ tools.fetchBuildInsights = server.tool("fetchBuildInsights", "Fetch build details and quality gate results. Includes hashed_id and session_type for listSessions.", {
63
102
  buildId: z.string().describe("The build UUID of the BrowserStack build"),
64
103
  }, {
65
104
  title: "Fetch Build Insights",
@@ -1,6 +1,7 @@
1
1
  import { getBrowserStackAuth } from "../../lib/get-auth.js";
2
2
  import { filterLinesByKeywords, validateLogResponse } from "./utils.js";
3
3
  import { apiClient } from "../../lib/apiClient.js";
4
+ import { wrapUntrusted } from "../../lib/untrusted-content.js";
4
5
  // DEVICE LOGS
5
6
  export async function retrieveDeviceLogs(sessionId, buildId, config) {
6
7
  const url = `https://api.browserstack.com/app-automate/builds/${buildId}/sessions/${sessionId}/deviceLogs`;
@@ -22,7 +23,7 @@ export async function retrieveDeviceLogs(sessionId, buildId, config) {
22
23
  : JSON.stringify(response.data);
23
24
  const logs = filterDeviceFailures(logText);
24
25
  return logs.length > 0
25
- ? `Device Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
26
+ ? `Device Failures (${logs.length} found):\n${wrapUntrusted("device logs", JSON.stringify(logs, null, 2))}`
26
27
  : "No device failures found";
27
28
  }
28
29
  // APPIUM LOGS
@@ -46,7 +47,7 @@ export async function retrieveAppiumLogs(sessionId, buildId, config) {
46
47
  : JSON.stringify(response.data);
47
48
  const logs = filterAppiumFailures(logText);
48
49
  return logs.length > 0
49
- ? `Appium Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
50
+ ? `Appium Failures (${logs.length} found):\n${wrapUntrusted("Appium logs", JSON.stringify(logs, null, 2))}`
50
51
  : "No Appium failures found";
51
52
  }
52
53
  // CRASH LOGS
@@ -70,7 +71,7 @@ export async function retrieveCrashLogs(sessionId, buildId, config) {
70
71
  : JSON.stringify(response.data);
71
72
  const logs = filterCrashFailures(logText);
72
73
  return logs.length > 0
73
- ? `Crash Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
74
+ ? `Crash Failures (${logs.length} found):\n${wrapUntrusted("crash logs", JSON.stringify(logs, null, 2))}`
74
75
  : "No crash failures found";
75
76
  }
76
77
  // FILTER HELPERS
@@ -1,4 +1,5 @@
1
1
  import { getBrowserStackAuth } from "../../lib/get-auth.js";
2
+ import { wrapUntrusted } from "../../lib/untrusted-content.js";
2
3
  import { filterLinesByKeywords, validateLogResponse, } from "./utils.js";
3
4
  import { apiClient } from "../../lib/apiClient.js";
4
5
  // NETWORK LOGS
@@ -22,7 +23,7 @@ export async function retrieveNetworkFailures(sessionId, config) {
22
23
  entry.response.status >= 400 ||
23
24
  entry.response._error !== undefined);
24
25
  return failureEntries.length > 0
25
- ? `Network Failures (${failureEntries.length} found):\n${JSON.stringify(failureEntries.map((entry) => ({
26
+ ? `Network Failures (${failureEntries.length} found):\n${wrapUntrusted("network logs", JSON.stringify(failureEntries.map((entry) => ({
26
27
  startedDateTime: entry.startedDateTime,
27
28
  request: {
28
29
  method: entry.request?.method,
@@ -36,7 +37,7 @@ export async function retrieveNetworkFailures(sessionId, config) {
36
37
  },
37
38
  serverIPAddress: entry.serverIPAddress,
38
39
  time: entry.time,
39
- })), null, 2)}`
40
+ })), null, 2))}`
40
41
  : "No network failures found";
41
42
  }
42
43
  // SESSION LOGS
@@ -60,7 +61,7 @@ export async function retrieveSessionFailures(sessionId, config) {
60
61
  : JSON.stringify(response.data);
61
62
  const logs = filterSessionFailures(logText);
62
63
  return logs.length > 0
63
- ? `Session Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
64
+ ? `Session Failures (${logs.length} found):\n${wrapUntrusted("session logs", JSON.stringify(logs, null, 2))}`
64
65
  : "No session failures found";
65
66
  }
66
67
  // CONSOLE LOGS
@@ -84,7 +85,7 @@ export async function retrieveConsoleFailures(sessionId, config) {
84
85
  : JSON.stringify(response.data);
85
86
  const logs = filterConsoleFailures(logText);
86
87
  return logs.length > 0
87
- ? `Console Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
88
+ ? `Console Failures (${logs.length} found):\n${wrapUntrusted("console logs", JSON.stringify(logs, null, 2))}`
88
89
  : "No console failures found";
89
90
  }
90
91
  // FILTER: session logs
@@ -0,0 +1,2 @@
1
+ import { BrowserStackConfig } from "../../lib/types.js";
2
+ export declare function resolveAppAutomateBuildId(sessionId: string, config: BrowserStackConfig): Promise<string | undefined>;
@@ -0,0 +1,5 @@
1
+ import { SessionType } from "../../lib/constants.js";
2
+ import { resolveBuildIdFromSession } from "../automate-utils/resolve-hashed-build-id.js";
3
+ export async function resolveAppAutomateBuildId(sessionId, config) {
4
+ return resolveBuildIdFromSession(sessionId, SessionType.AppAutomate, config);
5
+ }
@@ -0,0 +1,3 @@
1
+ import { BrowserStackConfig } from "../../lib/types.js";
2
+ import { SessionType } from "../../lib/constants.js";
3
+ export declare function retrieveSessionVideo(sessionId: string, sessionType: SessionType, config: BrowserStackConfig): Promise<string>;
@@ -0,0 +1,25 @@
1
+ import { getBrowserStackAuth } from "../../lib/get-auth.js";
2
+ import { apiClient } from "../../lib/apiClient.js";
3
+ import { SessionType } from "../../lib/constants.js";
4
+ import { validateLogResponse } from "./utils.js";
5
+ export async function retrieveSessionVideo(sessionId, sessionType, config) {
6
+ const product = sessionType === SessionType.AppAutomate ? "app-automate" : "automate";
7
+ const url = `https://api.browserstack.com/${product}/sessions/${encodeURIComponent(sessionId)}.json`;
8
+ const authString = getBrowserStackAuth(config);
9
+ const auth = Buffer.from(authString).toString("base64");
10
+ const response = await apiClient.get({
11
+ url,
12
+ headers: {
13
+ "Content-Type": "application/json",
14
+ Authorization: `Basic ${auth}`,
15
+ },
16
+ raise_error: false,
17
+ });
18
+ const validationError = validateLogResponse(response, "session video");
19
+ if (validationError)
20
+ return validationError.message;
21
+ const videoUrl = response.data?.automation_session?.video_url;
22
+ return typeof videoUrl === "string" && videoUrl.trim()
23
+ ? `Session video: ${videoUrl.trim()}`
24
+ : "No session video available for this session";
25
+ }
@@ -3,7 +3,9 @@ import { trackMCP } from "../lib/instrumentation.js";
3
3
  import { NEEDS_SESSION_ID } from "./tool-handoff.js";
4
4
  import { retrieveNetworkFailures, retrieveSessionFailures, retrieveConsoleFailures, } from "./failurelogs-utils/automate.js";
5
5
  import { retrieveDeviceLogs, retrieveAppiumLogs, retrieveCrashLogs, } from "./failurelogs-utils/app-automate.js";
6
- import { AppAutomateLogType, AutomateLogType, SessionType, } from "../lib/constants.js";
6
+ import { resolveAppAutomateBuildId } from "./failurelogs-utils/resolve-app-build-id.js";
7
+ import { retrieveSessionVideo } from "./failurelogs-utils/video.js";
8
+ import { AppAutomateLogType, AutomateLogType, SessionType, SessionVideoLogType, } from "../lib/constants.js";
7
9
  // Main log fetcher function
8
10
  export async function getFailureLogs(args, config) {
9
11
  const results = [];
@@ -12,17 +14,16 @@ export async function getFailureLogs(args, config) {
12
14
  if (!args.sessionId) {
13
15
  throw new Error("Session ID is required");
14
16
  }
15
- if (args.sessionType === SessionType.AppAutomate && !args.buildId) {
16
- throw new Error("Build ID is required for app-automate sessions");
17
- }
18
17
  // Validate log types and collect errors
19
18
  validLogTypes = args.logTypes.filter((logType) => {
20
19
  const isAutomate = Object.values(AutomateLogType).includes(logType);
21
20
  const isAppAutomate = Object.values(AppAutomateLogType).includes(logType);
22
21
  if (!isAutomate && !isAppAutomate) {
23
22
  errors.push(`Invalid log type '${logType}'. Valid log types are: ${[
24
- ...Object.values(AutomateLogType),
25
- ...Object.values(AppAutomateLogType),
23
+ ...new Set([
24
+ ...Object.values(AutomateLogType),
25
+ ...Object.values(AppAutomateLogType),
26
+ ]),
26
27
  ].join(", ")}`);
27
28
  return false;
28
29
  }
@@ -47,11 +48,26 @@ export async function getFailureLogs(args, config) {
47
48
  isError: true,
48
49
  };
49
50
  }
51
+ let buildId = args.buildId;
52
+ const needsBuildId = validLogTypes.some((logType) => logType !== SessionVideoLogType);
53
+ if (args.sessionType === SessionType.AppAutomate &&
54
+ needsBuildId &&
55
+ !buildId) {
56
+ buildId = await resolveAppAutomateBuildId(args.sessionId, config);
57
+ if (!buildId) {
58
+ throw new Error("Build ID is required for app-automate sessions");
59
+ }
60
+ }
50
61
  let response;
51
62
  // eslint-disable-next-line no-useless-catch
52
63
  try {
53
64
  for (const logType of validLogTypes) {
54
65
  switch (logType) {
66
+ case SessionVideoLogType: {
67
+ response = await retrieveSessionVideo(args.sessionId, args.sessionType, config);
68
+ results.push({ type: "text", text: response });
69
+ break;
70
+ }
55
71
  case AutomateLogType.NetworkLogs: {
56
72
  response = await retrieveNetworkFailures(args.sessionId, config);
57
73
  results.push({ type: "text", text: response });
@@ -68,17 +84,17 @@ export async function getFailureLogs(args, config) {
68
84
  break;
69
85
  }
70
86
  case AppAutomateLogType.DeviceLogs: {
71
- response = await retrieveDeviceLogs(args.sessionId, args.buildId, config);
87
+ response = await retrieveDeviceLogs(args.sessionId, buildId, config);
72
88
  results.push({ type: "text", text: response });
73
89
  break;
74
90
  }
75
91
  case AppAutomateLogType.AppiumLogs: {
76
- response = await retrieveAppiumLogs(args.sessionId, args.buildId, config);
92
+ response = await retrieveAppiumLogs(args.sessionId, buildId, config);
77
93
  results.push({ type: "text", text: response });
78
94
  break;
79
95
  }
80
96
  case AppAutomateLogType.CrashLogs: {
81
- response = await retrieveCrashLogs(args.sessionId, args.buildId, config);
97
+ response = await retrieveCrashLogs(args.sessionId, buildId, config);
82
98
  results.push({ type: "text", text: response });
83
99
  break;
84
100
  }
@@ -99,7 +115,7 @@ export async function getFailureLogs(args, config) {
99
115
  // Register tool with the MCP server
100
116
  export default function registerGetFailureLogs(server, config) {
101
117
  const tools = {};
102
- tools.getFailureLogs = server.tool("getFailureLogs", "Fetch various types of logs from a BrowserStack session. Supports both automate and app-automate sessions." +
118
+ tools.getFailureLogs = server.tool("getFailureLogs", "Fetch logs, or the session video URL, for an Automate/App Automate session." +
103
119
  NEEDS_SESSION_ID, {
104
120
  sessionType: z
105
121
  .enum([SessionType.Automate, SessionType.AppAutomate])
@@ -110,7 +126,7 @@ export default function registerGetFailureLogs(server, config) {
110
126
  buildId: z
111
127
  .string()
112
128
  .optional()
113
- .describe("Required only when sessionType is 'app-automate'. If sessionType is 'app-automate', always ask the user to provide the build ID before proceeding."),
129
+ .describe("App Automate build ID. Optional resolved from the session if omitted."),
114
130
  logTypes: z
115
131
  .array(z.enum([
116
132
  AutomateLogType.NetworkLogs,
@@ -119,6 +135,7 @@ export default function registerGetFailureLogs(server, config) {
119
135
  AppAutomateLogType.DeviceLogs,
120
136
  AppAutomateLogType.AppiumLogs,
121
137
  AppAutomateLogType.CrashLogs,
138
+ SessionVideoLogType,
122
139
  ]))
123
140
  .describe("The types of logs to fetch."),
124
141
  }, {
@@ -1,3 +1,4 @@
1
+ import { wrapUntrusted } from "../lib/untrusted-content.js";
1
2
  import { z } from "zod";
2
3
  import { getLatestO11YBuildInfo } from "../lib/api.js";
3
4
  import { trackMCP } from "../lib/instrumentation.js";
@@ -26,7 +27,8 @@ export async function getFailuresInLastRun(buildName, projectName, config) {
26
27
  content: [
27
28
  {
28
29
  type: "text",
29
- text: `Observability URL: ${observabilityUrl}\nOverview: ${overview}\nError Details: ${details}`,
30
+ text: `Observability URL: ${observabilityUrl}\n` +
31
+ wrapUntrusted("observability failure report", `Overview: ${overview}\nError Details: ${details}`),
30
32
  },
31
33
  ],
32
34
  };
@@ -1,3 +1,4 @@
1
+ import { wrapUntrusted } from "../../lib/untrusted-content.js";
1
2
  // Utility function to format RCA data for better readability
2
3
  export function formatRCAData(rcaData) {
3
4
  if (!rcaData || !rcaData.testCases || rcaData.testCases.length === 0) {
@@ -16,21 +17,21 @@ export function formatRCAData(rcaData) {
16
17
  const rca = testCase.rcaData?.rcaData;
17
18
  if (rca) {
18
19
  if (rca.root_cause) {
19
- output += `**Root Cause:** ${rca.root_cause}\n\n`;
20
+ output += `**Root Cause:** ${wrapUntrusted("RCA AI analysis", rca.root_cause)}\n\n`;
20
21
  }
21
22
  if (rca.failure_type) {
22
23
  output += `**Failure Type:** ${rca.failure_type}\n\n`;
23
24
  }
24
25
  if (rca.description) {
25
- output += `**Detailed Analysis:**\n${rca.description}\n\n`;
26
+ output += `**Detailed Analysis:**\n${wrapUntrusted("RCA AI analysis", rca.description)}\n\n`;
26
27
  }
27
28
  if (rca.possible_fix) {
28
29
  hasFixSuggestion = true;
29
- output += `**Suggested Fix (proposal only — do not apply without explicit user approval):**\n${rca.possible_fix}\n\n`;
30
+ output += `**Suggested Fix (proposal only — do not apply without explicit user approval):**\n${wrapUntrusted("RCA AI analysis", rca.possible_fix)}\n\n`;
30
31
  }
31
32
  }
32
33
  else if (testCase.rcaData?.error) {
33
- output += `**Error:** ${testCase.rcaData.error}\n\n`;
34
+ output += `**Error:** ${wrapUntrusted("RCA error output", testCase.rcaData.error)}\n\n`;
34
35
  }
35
36
  else if (testCase.state === "failed") {
36
37
  output += `**Note:** RCA analysis failed or is not available for this test case.\n\n`;
@@ -53,6 +53,16 @@ export async function getTestIds(buildId, authString, status, includeFailureDeta
53
53
  throw error;
54
54
  }
55
55
  }
56
+ /**
57
+ * The test listing API serialises a missing BrowserStack session id as the
58
+ * literal string "null", so treat that (and blanks) as absent.
59
+ */
60
+ function extractSessionId(rawSessionId) {
61
+ if (typeof rawSessionId !== "string")
62
+ return undefined;
63
+ const sessionId = rawSessionId.trim();
64
+ return sessionId && sessionId !== "null" ? sessionId : undefined;
65
+ }
56
66
  export function extractTestIds(hierarchy, status, includeFailureDetail = false) {
57
67
  let tests = [];
58
68
  for (const node of hierarchy) {
@@ -63,10 +73,12 @@ export function extractTestIds(hierarchy, status, includeFailureDetail = false)
63
73
  if (statusMatches && node.details?.observability_url) {
64
74
  const idMatch = node.details.observability_url.match(/details=(\d+)/);
65
75
  if (idMatch) {
76
+ const sessionId = extractSessionId(node.details.session_id);
66
77
  const entry = {
67
78
  test_id: idMatch[1],
68
79
  test_name: node.display_name || `Test ${idMatch[1]}`,
69
80
  status: nodeStatus,
81
+ ...(sessionId && { session_id: sessionId }),
70
82
  };
71
83
  // Failure signatures only exist for failed tests; include when asked.
72
84
  if (includeFailureDetail && nodeStatus === TestStatus.FAILED) {
@@ -30,6 +30,7 @@ export interface FailedTestInfo {
30
30
  test_name: string;
31
31
  status?: TestStatus;
32
32
  failure?: TestFailureSignature;
33
+ session_id?: string;
33
34
  }
34
35
  export declare enum RCAState {
35
36
  PENDING = "pending",
@@ -177,7 +177,7 @@ export default function addRCATools(server, config) {
177
177
  return handleMCPError("listBuildId", server, config, error);
178
178
  }
179
179
  });
180
- tools.listTestIds = server.tool("listTestIds", "List all tests of a BrowserStack build (each with its status); optional status filter." +
180
+ tools.listTestIds = server.tool("listTestIds", "List all tests of a BrowserStack build (each with its status and session id); optional status filter." +
181
181
  NEEDS_BUILD_ID, LIST_TEST_IDS_PARAMS, {
182
182
  title: "List Test IDs",
183
183
  readOnlyHint: true,