@browserstack/mcp-server 1.4.0-beta.2 → 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 (49) hide show
  1. package/README.md +43 -29
  2. package/dist/config.d.ts +4 -1
  3. package/dist/config.js +23 -2
  4. package/dist/lib/constants.d.ts +3 -0
  5. package/dist/lib/constants.js +3 -0
  6. package/dist/lib/untrusted-content.d.ts +15 -0
  7. package/dist/lib/untrusted-content.js +24 -0
  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/ask-browserstack/central-oauth.d.ts +7 -1
  14. package/dist/tools/ask-browserstack/central-oauth.js +25 -19
  15. package/dist/tools/ask-browserstack/config.d.ts +7 -1
  16. package/dist/tools/ask-browserstack/config.js +11 -5
  17. package/dist/tools/ask-browserstack/register.js +14 -1
  18. package/dist/tools/ask-browserstack/stream.js +9 -10
  19. package/dist/tools/ask-browserstack/types.d.ts +1 -1
  20. package/dist/tools/ask-browserstack/types.js +5 -1
  21. package/dist/tools/automate-utils/list-session-ids.d.ts +28 -0
  22. package/dist/tools/automate-utils/list-session-ids.js +87 -0
  23. package/dist/tools/automate-utils/resolve-hashed-build-id.d.ts +30 -0
  24. package/dist/tools/automate-utils/resolve-hashed-build-id.js +124 -0
  25. package/dist/tools/automate.d.ts +7 -0
  26. package/dist/tools/automate.js +104 -1
  27. package/dist/tools/build-insights.js +40 -1
  28. package/dist/tools/failurelogs-utils/app-automate.js +4 -3
  29. package/dist/tools/failurelogs-utils/automate.js +5 -4
  30. package/dist/tools/failurelogs-utils/resolve-app-build-id.d.ts +2 -0
  31. package/dist/tools/failurelogs-utils/resolve-app-build-id.js +5 -0
  32. package/dist/tools/failurelogs-utils/video.d.ts +3 -0
  33. package/dist/tools/failurelogs-utils/video.js +25 -0
  34. package/dist/tools/get-failure-logs.js +28 -11
  35. package/dist/tools/observability.js +3 -1
  36. package/dist/tools/rca-agent-utils/format-rca.js +5 -4
  37. package/dist/tools/rca-agent-utils/get-failed-test-id.js +12 -0
  38. package/dist/tools/rca-agent-utils/types.d.ts +1 -0
  39. package/dist/tools/rca-agent.js +1 -1
  40. package/dist/tools/review-agent.js +2 -1
  41. package/dist/tools/sdk-utils/common/constants.d.ts +1 -1
  42. package/dist/tools/sdk-utils/common/constants.js +2 -1
  43. package/dist/tools/selfheal.js +1 -1
  44. package/dist/tools/testmanagement-utils/testcase-from-file.js +2 -1
  45. package/dist/tools/testmanagement-utils/upload-file.js +16 -2
  46. package/dist/tools/testmanagement.js +10 -6
  47. package/dist/tools/tool-handoff.d.ts +30 -1
  48. package/dist/tools/tool-handoff.js +40 -9
  49. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import appConfig from "../../config.js";
1
2
  import logger from "../../logger.js";
2
3
  /**
3
4
  * Where Atlas lives, and the timeout ladder.
@@ -23,7 +24,13 @@ export const ELICITATION_TIMEOUT_MS = 270_000;
23
24
  /** Thrown for anything this tool refuses to attempt. Never carries a credential. */
24
25
  export class AskError extends Error {
25
26
  }
26
- /** Off by default is wrong for a shipped feature, but a kill switch is not. */
27
+ /**
28
+ * Off by default is wrong for a shipped feature, but a kill switch is not.
29
+ *
30
+ * The only setting here still read from `process.env` per call, and deliberately: a kill
31
+ * switch that needs a process restart is slowest exactly when it is needed fastest. The
32
+ * other three are on the config singleton (rules/tool-design.md).
33
+ */
27
34
  export function isEnabled() {
28
35
  return (process.env.ASK_BROWSERSTACK_DISABLED || "").toLowerCase() !== "true";
29
36
  }
@@ -41,8 +48,7 @@ export function isEnabled() {
41
48
  * run. This flag only removes the blanket refusal.
42
49
  */
43
50
  export function allowRemoteRelay() {
44
- return ((process.env.ASK_BROWSERSTACK_ALLOW_REMOTE_RELAY || "").toLowerCase() ===
45
- "true");
51
+ return appConfig.ASK_BROWSERSTACK_ALLOW_REMOTE_RELAY;
46
52
  }
47
53
  /**
48
54
  * ============================================================================
@@ -111,7 +117,7 @@ function announce(what, url, source) {
111
117
  * no selector: one default, one override.
112
118
  */
113
119
  export function atlasBaseUrl() {
114
- const explicit = process.env.ASK_BROWSERSTACK_ATLAS_URL;
120
+ const explicit = appConfig.ASK_BROWSERSTACK_ATLAS_URL;
115
121
  const url = explicit && explicit.trim() ? trimUrl(explicit) : DEFAULT_ATLAS_URL;
116
122
  announce("Atlas", url, explicit && explicit.trim() ? "env" : "default");
117
123
  return url;
@@ -127,7 +133,7 @@ export function agentUrl() {
127
133
  * the only way in. Same two rungs as the host, and the same staging default.
128
134
  */
129
135
  export function authTokenUrl() {
130
- const explicit = process.env.ASK_BROWSERSTACK_AUTH_TOKEN_URL;
136
+ const explicit = appConfig.ASK_BROWSERSTACK_AUTH_TOKEN_URL;
131
137
  const url = explicit && explicit.trim() ? trimUrl(explicit) : DEFAULT_AUTH_TOKEN_URL;
132
138
  announce("auth token endpoint", url, explicit && explicit.trim() ? "env" : "default");
133
139
  return url;
@@ -312,7 +312,7 @@ export function addAskBrowserStackAITool(server, deps, config) {
312
312
  tools.askBrowserStackAI = server.tool("askBrowserStackAI", DESCRIPTION, {
313
313
  product: z
314
314
  .enum(PRODUCTS)
315
- .describe("Which product to work in: tm (Test Management), a11y (Accessibility), " +
315
+ .describe("Which product to work in: tm (Test Management), " +
316
316
  "tra (Test Reporting & Analytics)."),
317
317
  query: z
318
318
  .string()
@@ -323,6 +323,11 @@ export function addAskBrowserStackAITool(server, deps, config) {
323
323
  // sets it false: consent is not a licence to delete.
324
324
  readOnlyHint: false,
325
325
  destructiveHint: false,
326
+ // openWorldHint: the agent fans out to product APIs chosen at runtime, so the set of
327
+ // effects is not knowable from this schema. idempotentHint false because a repeated
328
+ // call can create a second record — the relay asks again, it does not dedupe.
329
+ openWorldHint: true,
330
+ idempotentHint: false,
326
331
  title: "Ask BrowserStack AI (Alpha)",
327
332
  }, async ({ product, query }, extra) => {
328
333
  track("askBrowserStackAI");
@@ -371,6 +376,14 @@ export function addAskBrowserStackAITool(server, deps, config) {
371
376
  ? error.message
372
377
  : String(error);
373
378
  logger.error("askBrowserStackAI failed: %s", message);
379
+ // Error telemetry, in the same never-fatal shape as the success-path `track()`:
380
+ // a failing tool call must not be made worse by a failing analytics call.
381
+ try {
382
+ trackMCP("askBrowserStackAI", server.server.getClientVersion(), error, config);
383
+ }
384
+ catch {
385
+ /* ignore */
386
+ }
374
387
  // No `canElicit` argument: the request never left this process, so whether the
375
388
  // client could have been prompted is not what the reader needs to know.
376
389
  return toResult(errorResult(message, approvals));
@@ -22,6 +22,7 @@
22
22
  * is a pipe. Keeping the judgement out of the transport is why swapping A2 for A1 does
23
23
  * not risk the fail-closed behaviour.
24
24
  */
25
+ import { apiClient } from "../../lib/apiClient.js";
25
26
  import logger from "../../logger.js";
26
27
  import { AskError } from "./config.js";
27
28
  /**
@@ -208,15 +209,16 @@ export function fetchAgentStreamTransport(timeoutMs = WHOLE_RUN_TIMEOUT_MS) {
208
209
  /** The decision POST. 30s, because it is an ordinary short request. */
209
210
  export function fetchDecisionTransport(timeoutMs = 30_000) {
210
211
  return async (url, headers, body) => {
211
- const controller = new AbortController();
212
- const timer = setTimeout(() => controller.abort(), timeoutMs);
213
212
  try {
214
- const response = await fetch(url, {
215
- method: "POST",
213
+ // Through `apiClient` per rules/security.md. `raise_error: false` because the caller
214
+ // reads the STATUS: a 404 (run gone) and a 409 (already decided) are both answers,
215
+ // and a thrown AxiosError would collapse them into the unreachable case below.
216
+ const response = await apiClient.post({
217
+ url,
216
218
  headers,
217
- body: JSON.stringify(body),
218
- redirect: "manual",
219
- signal: controller.signal,
219
+ body,
220
+ timeout: timeoutMs,
221
+ raise_error: false,
220
222
  });
221
223
  return response.status;
222
224
  }
@@ -226,9 +228,6 @@ export function fetchDecisionTransport(timeoutMs = 30_000) {
226
228
  // the caller can say that rather than implying a human refused.
227
229
  return 0;
228
230
  }
229
- finally {
230
- clearTimeout(timer);
231
- }
232
231
  };
233
232
  }
234
233
  /** `POST /agent/{run_id}/permission`, built from the base URL the tool already resolved. */
@@ -6,7 +6,7 @@
6
6
  * different repo, at the same time. A field renamed here to read better is a field the
7
7
  * other half will never send. Nothing here changes without changing that document first.
8
8
  */
9
- export declare const PRODUCTS: readonly ["tm", "a11y", "tra"];
9
+ export declare const PRODUCTS: readonly ["tm", "tra"];
10
10
  export type Product = (typeof PRODUCTS)[number];
11
11
  /** CONTRACT §2 — what Atlas emits on the run's stream when its gate needs a human. */
12
12
  export interface PermissionAsk {
@@ -6,5 +6,9 @@
6
6
  * different repo, at the same time. A field renamed here to read better is a field the
7
7
  * other half will never send. Nothing here changes without changing that document first.
8
8
  */
9
- export const PRODUCTS = ["tm", "a11y", "tra"];
9
+ // a11y is deliberately ABSENT while Ask AI is in limited alpha. Atlas itself serves the
10
+ // product; this tool just does not offer it yet. Re-adding it means this list, the `product`
11
+ // describe text in register.ts, and the two a11y handoffs in tool-handoff.ts — which stop
12
+ // pointing here precisely because the call would now be rejected.
13
+ export const PRODUCTS = ["tm", "tra"];
10
14
  export const ASK_STATUSES = ["ok", "blocked", "error", "rate_limited"];
@@ -0,0 +1,28 @@
1
+ import { SessionType } from "../../lib/constants.js";
2
+ import { BrowserStackConfig } from "../../lib/types.js";
3
+ export declare const DEFAULT_SESSION_LIST_LIMIT = 10;
4
+ /** The REST session list returned 404: no Automate/App Automate build has this hashed id. */
5
+ export declare class UnknownBuildError extends Error {
6
+ constructor(message: string);
7
+ }
8
+ export interface ListSessionIdsArgs {
9
+ sessionType: SessionType;
10
+ buildId: string;
11
+ limit?: number;
12
+ offset?: number;
13
+ status?: string;
14
+ }
15
+ export interface SessionIdRecord {
16
+ sessionId: string;
17
+ name?: string;
18
+ status?: string;
19
+ os?: string;
20
+ osVersion?: string;
21
+ browser?: string;
22
+ device?: string | null;
23
+ browserUrl?: string;
24
+ videoUrl?: string;
25
+ }
26
+ export declare function sessionsListUrl(sessionType: SessionType, buildId: string): string;
27
+ export declare function mapSessionRecords(payload: unknown, statusFilter?: string): SessionIdRecord[];
28
+ export declare function listSessionIds(args: ListSessionIdsArgs, config: BrowserStackConfig): Promise<SessionIdRecord[]>;
@@ -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
  }
@@ -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