@browserstack/mcp-server 2.1.0 → 2.2.0-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 (40) hide show
  1. package/capability/loadtesting.capability-index.json +2978 -0
  2. package/capability/tm.capability-index.json +2 -1
  3. package/capability/tra.capability-index.json +52074 -0
  4. package/dist/config.d.ts +2 -27
  5. package/dist/config.js +6 -19
  6. package/dist/lib/central-oauth.d.ts +133 -0
  7. package/dist/lib/central-oauth.js +246 -0
  8. package/dist/lib/utils.js +0 -8
  9. package/dist/tools/ask-browserstack/central-oauth.d.ts +25 -46
  10. package/dist/tools/ask-browserstack/central-oauth.js +55 -177
  11. package/dist/tools/ask-browserstack/config.d.ts +14 -0
  12. package/dist/tools/ask-browserstack/config.js +16 -0
  13. package/dist/tools/ask-browserstack/register.d.ts +2 -3
  14. package/dist/tools/ask-browserstack/register.js +72 -219
  15. package/dist/tools/ask-browserstack/relay.js +17 -11
  16. package/dist/tools/ask-browserstack/stream.d.ts +5 -27
  17. package/dist/tools/ask-browserstack/stream.js +14 -25
  18. package/dist/tools/ask-browserstack/types.d.ts +3 -54
  19. package/dist/tools/ask-browserstack/types.js +1 -11
  20. package/dist/tools/automate-utils/fetch-screenshots.js +15 -17
  21. package/dist/tools/capability-registry/bind.js +43 -7
  22. package/dist/tools/capability-registry/discovery.js +3 -1
  23. package/dist/tools/capability-registry/egress.d.ts +12 -5
  24. package/dist/tools/capability-registry/egress.js +24 -1
  25. package/dist/tools/capability-registry/oauth.d.ts +63 -0
  26. package/dist/tools/capability-registry/oauth.js +176 -0
  27. package/dist/tools/capability-registry/register.js +289 -41
  28. package/dist/tools/capability-registry/resolve.d.ts +1 -1
  29. package/dist/tools/capability-registry/resolve.js +24 -3
  30. package/dist/tools/capability-registry/routing-token.d.ts +25 -0
  31. package/dist/tools/capability-registry/routing-token.js +87 -0
  32. package/dist/tools/capability-registry/search.d.ts +28 -1
  33. package/dist/tools/capability-registry/search.js +202 -4
  34. package/dist/tools/capability-registry/types.d.ts +42 -3
  35. package/dist/tools/testmanagement.js +5 -5
  36. package/dist/tools/tool-handoff.d.ts +15 -12
  37. package/dist/tools/tool-handoff.js +21 -18
  38. package/package.json +2 -1
  39. package/dist/tools/ask-browserstack/deferred.d.ts +0 -74
  40. package/dist/tools/ask-browserstack/deferred.js +0 -242
@@ -1,5 +1,15 @@
1
1
  /**
2
- * Mint a BrowserStack central-OAuth JWT from the caller's username and access key.
2
+ * Atlas's view of the central-OAuth mint.
3
+ *
4
+ * The MECHANISM — the form, the transport, the classification, the cache — moved to
5
+ * `src/lib/central-oauth.ts` when the capability registry needed the same exchange for
6
+ * products whose APIs take a Bearer JWT rather than `Api-Token`. Two minters would have
7
+ * drifted, and the one that drifted would have been the one with fewer tests.
8
+ *
9
+ * What stays here is everything ATLAS-SPECIFIC and nothing else: the scope pair, the skew
10
+ * that exists because Atlas holds the token for a whole run, and the messages — which say
11
+ * "nothing reached the agent" and name `ai_agent_notify`, and would be actively wrong in
12
+ * front of a capability-registry user.
3
13
  *
4
14
  * This replaces a shared delegation token, and the upgrade is not cosmetic.
5
15
  * `validate_delegation_token` refuses any token without `user.user_id`/`user.group_id`, so
@@ -7,24 +17,20 @@
7
17
  * user from signed claims rather than from anything we put in the request body, and reuses
8
18
  * this same JWT as its `egress_token` — so the product call a human approves runs as that
9
19
  * human, not as a shared service account.
10
- *
11
- * SECRET HYGIENE IS THE WHOLE POINT OF THIS MODULE, and Atlas's `central_oauth.py` learned
12
- * it the hard way: "The body can echo the credential back on some errors, so it is NOT
13
- * logged or raised — only the status." Neither the access key nor the minted token is ever
14
- * logged, returned, or put in an error message. Only a status code is.
15
20
  */
16
- import { createHash } from "node:crypto";
17
- import { apiClient } from "../../lib/apiClient.js";
21
+ import { CentralAuthError, mintCentralToken as mintShared, mintForm as mintFormShared, REQUESTED_EXPIRES_IN, } from "../../lib/central-oauth.js";
18
22
  import appConfig from "../../config.js";
19
23
  import logger from "../../logger.js";
20
24
  import { AGENT_TIMEOUT_MS, AskError } from "./config.js";
25
+ export { fetchTokenTransport, refusalIsAboutScope, REQUESTED_EXPIRES_IN, resetTokenCache, TOKEN_TIMEOUT_MS, } from "../../lib/central-oauth.js";
21
26
  /**
22
27
  * BOTH PARTS ARE REQUIRED, AND THERE IS NO FALLBACK TO ANOTHER SCOPE.
23
28
  *
24
29
  * `oauth_user_profile` stays because it is what makes the pair obtainable through the
25
- * username+access_key flow at all. `ai_agent_notify` is what Atlas matches on
26
- * (`delegation.required_scope`, checked as exact membership of the token's `scopes` claim in
27
- * `web/oauth.py`); both halves move together with Atlas.
30
+ * username+access_key flow at all — measured, not assumed: the paired scope mints, and the
31
+ * other half alone comes back `400 invalid_request`. `ai_agent_notify` is what Atlas matches
32
+ * on (`delegation.required_scope`, checked as exact membership of the token's `scopes` claim
33
+ * in `web/oauth.py`); both halves move together with Atlas.
28
34
  *
29
35
  * THIS SCOPE MAY SIMPLY NOT BE ISSUABLE TO US, and the reasons are worth stating rather than
30
36
  * discovering. From the merged `browserstack/railsApp#175367` (2026-08-24):
@@ -46,10 +52,11 @@ import { AGENT_TIMEOUT_MS, AskError } from "./config.js";
46
52
  * application — and it is reported as one, naming the scope. It is never retried with a
47
53
  * different scope: a silent downgrade to a different authorization is exactly the kind of
48
54
  * thing nobody notices until it matters.
55
+ *
56
+ * Named here rather than taken from the shared default, so that changing the registry's
57
+ * scopes can never silently change what Atlas is authorised for.
49
58
  */
50
59
  export const CENTRAL_SCOPE = "oauth_user_profile ai_agent_notify";
51
- /** What we ask for. The endpoint clamps to its own maximum, so the response wins. */
52
- export const REQUESTED_EXPIRES_IN = 3600;
53
60
  /**
54
61
  * Treat a token as stale this long before it actually expires.
55
62
  *
@@ -60,49 +67,6 @@ export const REQUESTED_EXPIRES_IN = 3600;
60
67
  * expired credential, which is the exact mid-flight expiry this cache exists to prevent.
61
68
  */
62
69
  export const REFRESH_SKEW_MS = AGENT_TIMEOUT_MS + 60_000;
63
- /** The token endpoint gets its own, much shorter budget than `/agent`. */
64
- export const TOKEN_TIMEOUT_MS = 15_000;
65
- /**
66
- * The OAuth2 error codes we are willing to read out of a failure body.
67
- *
68
- * `error` is a fixed enum token in the spec, so it cannot carry a credential; `error_description`
69
- * is free text and demonstrably CAN ("access_key <key> is invalid"), which is why only the
70
- * code is ever looked at and only when it is one of these. Anything else is ignored entirely
71
- * and the classification falls back to the status.
72
- */
73
- const SCOPE_ERROR_CODES = [
74
- "invalid_scope",
75
- "unauthorized_client",
76
- "invalid_request",
77
- ];
78
- const CREDENTIAL_ERROR_CODES = [
79
- "invalid_client",
80
- "invalid_grant",
81
- "access_denied",
82
- ];
83
- /**
84
- * Was this refusal about the SCOPE or about the CREDENTIAL?
85
- *
86
- * The two need completely different fixes — provisioning versus a password — so collapsing
87
- * them into one message sends someone to the wrong place entirely. Our form has five fields
88
- * and four of them are constants, so a refusal of the REQUEST (as opposed to the caller) can
89
- * only really be about the scope.
90
- *
91
- * Nothing from the body is ever surfaced; the code is used to classify and then discarded.
92
- */
93
- export function refusalIsAboutScope(status, body) {
94
- const payload = typeof body === "object" && body !== null
95
- ? body
96
- : {};
97
- const code = typeof payload.error === "string" ? payload.error : "";
98
- if (SCOPE_ERROR_CODES.includes(code))
99
- return true;
100
- if (CREDENTIAL_ERROR_CODES.includes(code))
101
- return false;
102
- // No usable code. OAuth2 answers a bad REQUEST with 400 and a bad CLIENT with 401/403, so
103
- // the status is the next best evidence.
104
- return status === 400;
105
- }
106
70
  /**
107
71
  * The ways authentication can fail, kept apart because a user cannot act on them otherwise.
108
72
  *
@@ -141,137 +105,51 @@ export const AUTH_SERVER_ERROR_DETAIL = (status) => `BrowserStack auth is unavai
141
105
  `BrowserStack auth is back.`;
142
106
  export const AUTH_UNUSABLE_DETAIL = (status) => `BrowserStack auth answered HTTP ${status} without issuing a token. NOTHING REACHED THE ` +
143
107
  `AGENT — no request was made, no prompt appeared and nothing was changed.`;
144
- const cache = new Map();
145
- /** Drop every cached token. For tests, and for a credential rotation. */
146
- export function resetTokenCache() {
147
- cache.clear();
148
- }
149
- /**
150
- * The cache key.
151
- *
152
- * Keyed on the access key so that ROTATING it mints immediately rather than leaving a
153
- * revoked credential working until expiry — but on a SHA-256 of it, never the value, so the
154
- * secret is not left sitting in a map key for the life of the process.
155
- */
156
- function cacheKey(url, credentials) {
157
- const digest = createHash("sha256")
158
- .update(credentials.accessKey)
159
- .digest("hex");
160
- return `${url} ${credentials.username} ${CENTRAL_SCOPE} ${digest}`;
161
- }
162
- /**
163
- * The token endpoint, through `apiClient` per rules/security.md — no bare `fetch`.
164
- *
165
- * `raise_error: false` keeps the status-first contract this transport has always had: the
166
- * caller distinguishes a 400 scope refusal from a 401 rejection from an unreachable host,
167
- * so a thrown AxiosError on any non-2xx would destroy the only signal it reads.
168
- */
169
- export function fetchTokenTransport(timeoutMs = TOKEN_TIMEOUT_MS) {
170
- return async (url, form) => {
171
- try {
172
- const response = await apiClient.post({
173
- url,
174
- headers: {
175
- "Content-Type": "application/x-www-form-urlencoded",
176
- Accept: "application/json",
177
- },
178
- body: new URLSearchParams(form).toString(),
179
- timeout: timeoutMs,
180
- raise_error: false,
181
- });
182
- return { status: response.status, body: response.data ?? null };
183
- }
184
- catch {
185
- // DNS, TLS, timeout — all of them mean "no token". The reason is deliberately not
186
- // carried: it can name the URL and, on some stacks, echo the request body.
187
- return { status: 0, body: null, error: "auth could not be reached" };
188
- }
189
- };
190
- }
191
- /** The exact form body of the `client_credentials` grant. */
108
+ /** The exact form body of the `client_credentials` grant, at Atlas's scope. */
192
109
  export function mintForm(credentials) {
193
- return {
194
- grant_type: "client_credentials",
195
- username: credentials.username,
196
- access_key: credentials.accessKey,
197
- scope: CENTRAL_SCOPE,
198
- expires_in: String(REQUESTED_EXPIRES_IN),
199
- };
110
+ return mintFormShared(credentials, CENTRAL_SCOPE, REQUESTED_EXPIRES_IN);
200
111
  }
201
- async function mintOnce(url, credentials, transport) {
202
- const response = await transport(url, mintForm(credentials));
203
- if (response.status === 0)
204
- throw new AskError(AUTH_UNREACHABLE_DETAIL);
205
- // 5xx BEFORE the refusal branch: a server error is not a refusal, and reading it as one
206
- // is worse than saying nothing — it names the caller's credentials as the fault.
207
- if (response.status >= 500) {
208
- throw new AskError(AUTH_SERVER_ERROR_DETAIL(response.status));
112
+ /** Every failure kind gets Atlas's own sentence; none of them carries the response body. */
113
+ function toAskError(error) {
114
+ if (!(error instanceof CentralAuthError))
115
+ return error;
116
+ switch (error.kind) {
117
+ case "no_credentials":
118
+ return new AskError("BrowserStack AI is not authenticated: BROWSERSTACK_USERNAME and " +
119
+ "BROWSERSTACK_ACCESS_KEY are required to sign in");
120
+ case "unreachable":
121
+ return new AskError(AUTH_UNREACHABLE_DETAIL);
122
+ case "server_error":
123
+ return new AskError(AUTH_SERVER_ERROR_DETAIL(error.status));
124
+ case "refused_scope":
125
+ return new AskError(AUTH_SCOPE_REFUSED_DETAIL(error.status));
126
+ case "refused_credentials":
127
+ return new AskError(AUTH_REJECTED_DETAIL(error.status));
128
+ default:
129
+ return new AskError(AUTH_UNUSABLE_DETAIL(error.status));
209
130
  }
210
- if (response.status !== 200) {
211
- // ONLY THE STATUS CROSSES. The body is read solely to tell a provisioning problem from a
212
- // credential one, and nothing out of it is ever put in the message — a non-200 body can
213
- // echo the access key straight back.
214
- throw new AskError(refusalIsAboutScope(response.status, response.body)
215
- ? AUTH_SCOPE_REFUSED_DETAIL(response.status)
216
- : AUTH_REJECTED_DETAIL(response.status));
217
- }
218
- const body = typeof response.body === "object" && response.body !== null
219
- ? response.body
220
- : {};
221
- const token = body.access_token;
222
- if (typeof token !== "string" || !token) {
223
- throw new AskError(AUTH_UNUSABLE_DETAIL(response.status));
224
- }
225
- // Trust the SERVER's lifetime over what we asked for — it clamps to its own maximum, and
226
- // caching for the requested hour when it granted less would hand out a dead token.
227
- const granted = Number(body.expires_in);
228
- const seconds = Number.isFinite(granted) && granted > 0 ? granted : REQUESTED_EXPIRES_IN;
229
- return { token, lifetimeMs: seconds * 1000 };
230
131
  }
231
132
  /**
232
133
  * Return a valid token, minting one only when the cache has nothing fresh.
233
134
  *
234
- * Minting per tool call would add a round trip to every request and make the token endpoint
235
- * a hot dependency of the whole surface.
135
+ * NOT CACHED IN HOSTED MODE. These tokens are per-user, attested credentials, and the
136
+ * process is shared by every tenant — `rules/multi-tenant-safety.md` forbids holding user
137
+ * data in module-level state there, so remote mode mints per call.
236
138
  */
237
139
  export async function mintCentralToken(url, credentials, transport, now = Date.now()) {
238
- // Refused before any network call, and by name: these ARE the auth credential now, not
239
- // merely attribution, so an empty one is our missing configuration rather than the user's
240
- // rejected password, and must not read like one.
241
- if (!credentials?.username || !credentials?.accessKey) {
242
- throw new AskError("BrowserStack AI is not authenticated: BROWSERSTACK_USERNAME and " +
243
- "BROWSERSTACK_ACCESS_KEY are required to sign in");
244
- }
245
- // NOT CACHED IN HOSTED MODE. These tokens are per-user, attested credentials, and the
246
- // process is shared by every tenant — `rules/multi-tenant-safety.md` forbids holding user
247
- // data in module-level state there, so remote mode mints per call. Keying on
248
- // username + sha256(accessKey) already means one user can never be SERVED another's token,
249
- // but containment is not the contract; not holding it at all is.
250
- if (appConfig.REMOTE_MCP) {
251
- return mintOnce(url, credentials, transport).then(({ token }) => {
252
- logger.info("askBrowserStackAI: signed in as %s", credentials.username);
253
- return token;
140
+ try {
141
+ return await mintShared({
142
+ url,
143
+ scope: CENTRAL_SCOPE,
144
+ credentials,
145
+ transport,
146
+ refreshSkewMs: REFRESH_SKEW_MS,
147
+ cacheEnabled: !appConfig.REMOTE_MCP,
148
+ now,
149
+ onMinted: (lifetimeMs) => logger.info("askBrowserStackAI: signed in as %s (lifetime %ss)", credentials.username, Math.round(lifetimeMs / 1000)),
254
150
  });
255
151
  }
256
- const key = cacheKey(url, credentials);
257
- const entry = cache.get(key);
258
- if (entry && entry.token && now < entry.expiresAt - REFRESH_SKEW_MS) {
259
- return entry.token;
152
+ catch (error) {
153
+ throw toAskError(error);
260
154
  }
261
- // Double-checked through a shared promise: concurrent callers await the same mint.
262
- if (entry?.inflight)
263
- return entry.inflight;
264
- const pending = mintOnce(url, credentials, transport)
265
- .then(({ token, lifetimeMs }) => {
266
- cache.set(key, { token, expiresAt: now + lifetimeMs });
267
- logger.info("askBrowserStackAI: signed in as %s (lifetime %ss)", credentials.username, Math.round(lifetimeMs / 1000));
268
- return token;
269
- })
270
- .catch((error) => {
271
- // Never leave a rejected promise cached, or every later call inherits this failure.
272
- cache.delete(key);
273
- throw error;
274
- });
275
- cache.set(key, { token: "", expiresAt: 0, inflight: pending });
276
- return pending;
277
155
  }
@@ -30,6 +30,20 @@ export declare class AskError extends Error {
30
30
  * other three are on the config singleton (rules/tool-design.md).
31
31
  */
32
32
  export declare function isEnabled(): boolean;
33
+ /**
34
+ * May the relay be offered in the hosted (`REMOTE_MCP`) deployment?
35
+ *
36
+ * OFF BY DEFAULT, because it depends on something outside this package: the host has to
37
+ * keep one `McpServer` alive per session. Stateless hosts build a fresh server per POST,
38
+ * and an elicitation answer — which arrives as a SEPARATE POST — then reaches an instance
39
+ * that never asked anything, leaving the real one suspended until it times out. So this
40
+ * must stay opt-in per deployment rather than become a default that silently hangs.
41
+ *
42
+ * Turning it on does NOT force the relay on: `relayMode` still asks whether THIS client
43
+ * declared the `elicitation` capability, and a client that did not still gets a read-only
44
+ * run. This flag only removes the blanket refusal.
45
+ */
46
+ export declare function allowRemoteRelay(): boolean;
33
47
  /**
34
48
  * ============================================================================
35
49
  * PRODUCTION DEFAULTS
@@ -34,6 +34,22 @@ export class AskError extends Error {
34
34
  export function isEnabled() {
35
35
  return (process.env.ASK_BROWSERSTACK_DISABLED || "").toLowerCase() !== "true";
36
36
  }
37
+ /**
38
+ * May the relay be offered in the hosted (`REMOTE_MCP`) deployment?
39
+ *
40
+ * OFF BY DEFAULT, because it depends on something outside this package: the host has to
41
+ * keep one `McpServer` alive per session. Stateless hosts build a fresh server per POST,
42
+ * and an elicitation answer — which arrives as a SEPARATE POST — then reaches an instance
43
+ * that never asked anything, leaving the real one suspended until it times out. So this
44
+ * must stay opt-in per deployment rather than become a default that silently hangs.
45
+ *
46
+ * Turning it on does NOT force the relay on: `relayMode` still asks whether THIS client
47
+ * declared the `elicitation` capability, and a client that did not still gets a read-only
48
+ * run. This flag only removes the blanket refusal.
49
+ */
50
+ export function allowRemoteRelay() {
51
+ return appConfig.ASK_BROWSERSTACK_ALLOW_REMOTE_RELAY;
52
+ }
37
53
  /**
38
54
  * ============================================================================
39
55
  * PRODUCTION DEFAULTS
@@ -26,7 +26,7 @@
26
26
  import { McpServer, RegisteredTool } from "@modelcontextprotocol/sdk/server/mcp.js";
27
27
  import { BrowserStackConfig } from "../../lib/types.js";
28
28
  import { Credentials } from "./egress.js";
29
- import type { AgentStreamTransport, DeferredTransport } from "./stream.js";
29
+ import type { AgentStreamTransport, DecisionTransport } from "./stream.js";
30
30
  import { RelayMode } from "./types.js";
31
31
  export interface AskDeps {
32
32
  /** Resolved per call: a deployment's host is configuration, not a constructor argument. */
@@ -52,8 +52,7 @@ export interface AskDeps {
52
52
  * — ask, elicit, decide, result — without a socket.
53
53
  */
54
54
  streamTransport?: AgentStreamTransport;
55
- /** The deferred START (one request, one JSON response). Substituted in tests. */
56
- deferredTransport?: DeferredTransport;
55
+ decisionTransport?: DecisionTransport;
57
56
  }
58
57
  export declare function relayMode(server: McpServer): RelayMode;
59
58
  export declare function addAskBrowserStackAITool(server: McpServer, deps: AskDeps, config?: BrowserStackConfig): Record<string, RegisteredTool>;