@browserstack/mcp-server 1.4.0-beta.3 → 1.4.1-beta.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.
Files changed (46) hide show
  1. package/README.md +45 -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/upload-validator.d.ts +3 -2
  7. package/dist/lib/upload-validator.js +18 -15
  8. package/dist/lib/version-resolver.d.ts +0 -5
  9. package/dist/lib/version-resolver.js +8 -2
  10. package/dist/logger.js +1 -10
  11. package/dist/tools/accessibility.js +4 -3
  12. package/dist/tools/accessiblity-utils/accessibility-rag.js +3 -1
  13. package/dist/tools/appautomate-utils/native-execution/constants.js +4 -2
  14. package/dist/tools/appautomate.js +3 -1
  15. package/dist/tools/applive.js +1 -1
  16. package/dist/tools/automate-utils/list-session-ids.d.ts +28 -0
  17. package/dist/tools/automate-utils/list-session-ids.js +87 -0
  18. package/dist/tools/automate-utils/resolve-hashed-build-id.d.ts +30 -0
  19. package/dist/tools/automate-utils/resolve-hashed-build-id.js +124 -0
  20. package/dist/tools/automate.d.ts +7 -0
  21. package/dist/tools/automate.js +104 -1
  22. package/dist/tools/bstack-sdk.js +2 -2
  23. package/dist/tools/build-insights.js +41 -2
  24. package/dist/tools/failurelogs-utils/app-automate.js +4 -3
  25. package/dist/tools/failurelogs-utils/automate.js +5 -4
  26. package/dist/tools/failurelogs-utils/resolve-app-build-id.d.ts +2 -0
  27. package/dist/tools/failurelogs-utils/resolve-app-build-id.js +5 -0
  28. package/dist/tools/failurelogs-utils/video.d.ts +3 -0
  29. package/dist/tools/failurelogs-utils/video.js +25 -0
  30. package/dist/tools/get-failure-logs.js +28 -11
  31. package/dist/tools/observability.js +3 -1
  32. package/dist/tools/percy-sdk.js +9 -9
  33. package/dist/tools/rca-agent-utils/format-rca.js +5 -4
  34. package/dist/tools/rca-agent-utils/get-failed-test-id.js +12 -0
  35. package/dist/tools/rca-agent-utils/types.d.ts +1 -0
  36. package/dist/tools/rca-agent.js +1 -1
  37. package/dist/tools/review-agent.js +2 -1
  38. package/dist/tools/sdk-utils/common/constants.d.ts +1 -1
  39. package/dist/tools/sdk-utils/common/constants.js +2 -1
  40. package/dist/tools/selfheal.js +1 -1
  41. package/dist/tools/testmanagement-utils/testcase-from-file.js +2 -1
  42. package/dist/tools/testmanagement-utils/upload-file.js +16 -2
  43. package/dist/tools/testmanagement.js +2 -2
  44. package/dist/tools/tool-handoff.d.ts +5 -1
  45. package/dist/tools/tool-handoff.js +7 -4
  46. package/package.json +1 -1
@@ -0,0 +1,87 @@
1
+ import { SessionType } from "../../lib/constants.js";
2
+ import { getBrowserStackAuth } from "../../lib/get-auth.js";
3
+ import { apiClient } from "../../lib/apiClient.js";
4
+ export const DEFAULT_SESSION_LIST_LIMIT = 10;
5
+ /** The REST session list returned 404: no Automate/App Automate build has this hashed id. */
6
+ export class UnknownBuildError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "UnknownBuildError";
10
+ }
11
+ }
12
+ export function sessionsListUrl(sessionType, buildId) {
13
+ const encodedBuildId = encodeURIComponent(buildId);
14
+ switch (sessionType) {
15
+ case SessionType.Automate:
16
+ return `https://api.browserstack.com/automate/builds/${encodedBuildId}/sessions.json`;
17
+ case SessionType.AppAutomate:
18
+ return `https://api-cloud.browserstack.com/app-automate/builds/${encodedBuildId}/sessions.json`;
19
+ default: {
20
+ const _exhaustive = sessionType;
21
+ throw new Error(`Unsupported session type: ${_exhaustive}`);
22
+ }
23
+ }
24
+ }
25
+ export function mapSessionRecords(payload, statusFilter) {
26
+ const items = Array.isArray(payload) ? payload : [];
27
+ const normalizedFilter = statusFilter?.trim().toLowerCase();
28
+ const records = [];
29
+ for (const item of items) {
30
+ const session = item?.automation_session;
31
+ if (!session) {
32
+ continue;
33
+ }
34
+ const sessionId = session.hashed_id?.trim();
35
+ if (!sessionId) {
36
+ continue;
37
+ }
38
+ if (normalizedFilter &&
39
+ (session.status ?? "").toLowerCase() !== normalizedFilter) {
40
+ continue;
41
+ }
42
+ records.push({
43
+ sessionId,
44
+ name: session.name,
45
+ status: session.status,
46
+ os: session.os,
47
+ osVersion: session.os_version,
48
+ browser: session.browser,
49
+ device: session.device,
50
+ browserUrl: session.browser_url,
51
+ videoUrl: session.video_url,
52
+ });
53
+ }
54
+ return records;
55
+ }
56
+ export async function listSessionIds(args, config) {
57
+ const buildId = args.buildId.trim();
58
+ if (!buildId) {
59
+ throw new Error("Hashed Automate/App Automate build ID is required");
60
+ }
61
+ const authString = getBrowserStackAuth(config);
62
+ const auth = Buffer.from(authString).toString("base64");
63
+ const limit = args.limit ?? DEFAULT_SESSION_LIST_LIMIT;
64
+ const params = { limit };
65
+ if (args.offset !== undefined) {
66
+ params.offset = args.offset;
67
+ }
68
+ const response = await apiClient.get({
69
+ url: sessionsListUrl(args.sessionType, buildId),
70
+ headers: {
71
+ "Content-Type": "application/json",
72
+ Authorization: `Basic ${auth}`,
73
+ },
74
+ params,
75
+ raise_error: false,
76
+ });
77
+ if (!response.ok) {
78
+ if (response.status === 404) {
79
+ throw new UnknownBuildError(`No ${args.sessionType} build found for id "${buildId}". ` +
80
+ "Pass the Automate/App Automate dashboard hashed build id or the " +
81
+ "observability build id from getBuildId / listBuildId, and check that " +
82
+ "sessionType matches the product the build ran on.");
83
+ }
84
+ throw new Error(`Failed to list sessions: ${response.status} ${response.statusText}`);
85
+ }
86
+ return mapSessionRecords(response.data, args.status);
87
+ }
@@ -0,0 +1,30 @@
1
+ import { SessionType } from "../../lib/constants.js";
2
+ import { BrowserStackConfig } from "../../lib/types.js";
3
+ export declare function isObservabilityBuildUuid(id: string): boolean;
4
+ export declare function isHashedBuildId(id: string): boolean;
5
+ export declare function sessionDetailsUrl(sessionType: SessionType, sessionId: string): string;
6
+ /**
7
+ * Resolve the hashed build id that a session belongs to via the Automate /
8
+ * App Automate session detail endpoint. Returns undefined when the session
9
+ * cannot be fetched or does not report a build.
10
+ */
11
+ export declare function resolveBuildIdFromSession(sessionId: string, sessionType: SessionType, config: BrowserStackConfig): Promise<string | undefined>;
12
+ /**
13
+ * Find any BrowserStack session id attached to an observability build by
14
+ * walking its test runs. Returns undefined when no test reports a session
15
+ * (e.g. JUnit-uploaded builds that never ran on BrowserStack).
16
+ */
17
+ export declare function findSessionIdForObservabilityBuild(observabilityBuildId: string, config: BrowserStackConfig): Promise<string | undefined>;
18
+ export interface ResolvedHashedBuildId {
19
+ hashedBuildId: string;
20
+ sessionId: string;
21
+ sessionType: SessionType;
22
+ }
23
+ /**
24
+ * Convert an observability build UUID into the Automate / App Automate hashed
25
+ * build id in two deterministic API calls: pick any session of the build from
26
+ * its test runs, then read `build_hashed_id` from that session's details.
27
+ *
28
+ * When `sessionType` is omitted, Automate is tried first, then App Automate.
29
+ */
30
+ export declare function resolveHashedBuildId(observabilityBuildId: string, config: BrowserStackConfig, sessionType?: SessionType): Promise<ResolvedHashedBuildId>;
@@ -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
  }
@@ -13,11 +13,11 @@ export function registerRunBrowserStackTestsTool(server, config) {
13
13
  idempotentHint: true,
14
14
  }, async (args) => {
15
15
  try {
16
- trackMCP("runTestsOnBrowserStack", server.server.getClientVersion(), config);
16
+ trackMCP("setupBrowserStackAutomateTests", server.server.getClientVersion(), undefined, config);
17
17
  return await runTestsOnBrowserStackHandler(args, config);
18
18
  }
19
19
  catch (error) {
20
- return handleMCPError("runTestsOnBrowserStack", server, config, error);
20
+ return handleMCPError("setupBrowserStackAutomateTests", server, config, error);
21
21
  }
22
22
  });
23
23
  return tools;
@@ -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",
@@ -69,7 +108,7 @@ export default function addBuildInsightsTools(server, config) {
69
108
  idempotentHint: true,
70
109
  }, async (args) => {
71
110
  try {
72
- trackMCP("fetchBuildInsights", server.server.getClientVersion(), config);
111
+ trackMCP("fetchBuildInsights", server.server.getClientVersion(), undefined, config);
73
112
  return await fetchBuildInsightsTool(args, config);
74
113
  }
75
114
  catch (error) {
@@ -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
+ }