@browserstack/mcp-server 1.4.0-beta.3 → 1.5.0-beta.10

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/capability/loadtesting.capability-index.json +1792 -0
  2. package/capability/tm.capability-index.json +20094 -0
  3. package/dist/config.d.ts +1 -4
  4. package/dist/config.js +2 -23
  5. package/dist/index.js +2 -5
  6. package/dist/server-factory.js +5 -5
  7. package/dist/tools/accessibility.js +2 -5
  8. package/dist/tools/capability-registry/bind.d.ts +29 -0
  9. package/dist/tools/capability-registry/bind.js +134 -0
  10. package/dist/tools/capability-registry/config.d.ts +62 -0
  11. package/dist/tools/capability-registry/config.js +218 -0
  12. package/dist/tools/capability-registry/discovery.d.ts +44 -0
  13. package/dist/tools/capability-registry/discovery.js +99 -0
  14. package/dist/tools/capability-registry/egress.d.ts +44 -0
  15. package/dist/tools/capability-registry/egress.js +128 -0
  16. package/dist/tools/capability-registry/index-loader.d.ts +133 -0
  17. package/dist/tools/capability-registry/index-loader.js +369 -0
  18. package/dist/tools/capability-registry/register.d.ts +34 -0
  19. package/dist/tools/capability-registry/register.js +396 -0
  20. package/dist/tools/capability-registry/resolve.d.ts +38 -0
  21. package/dist/tools/capability-registry/resolve.js +45 -0
  22. package/dist/tools/capability-registry/search.d.ts +97 -0
  23. package/dist/tools/capability-registry/search.js +527 -0
  24. package/dist/tools/capability-registry/types.d.ts +232 -0
  25. package/dist/tools/capability-registry/types.js +33 -0
  26. package/dist/tools/get-failure-logs.js +1 -3
  27. package/dist/tools/rca-agent.js +2 -5
  28. package/dist/tools/selfheal.js +2 -5
  29. package/dist/tools/testmanagement.js +15 -37
  30. package/package.json +3 -2
  31. package/dist/tools/ask-browserstack/central-oauth.d.ts +0 -120
  32. package/dist/tools/ask-browserstack/central-oauth.js +0 -277
  33. package/dist/tools/ask-browserstack/config.d.ts +0 -102
  34. package/dist/tools/ask-browserstack/config.js +0 -140
  35. package/dist/tools/ask-browserstack/egress.d.ts +0 -34
  36. package/dist/tools/ask-browserstack/egress.js +0 -31
  37. package/dist/tools/ask-browserstack/register.d.ts +0 -61
  38. package/dist/tools/ask-browserstack/register.js +0 -416
  39. package/dist/tools/ask-browserstack/relay.d.ts +0 -201
  40. package/dist/tools/ask-browserstack/relay.js +0 -577
  41. package/dist/tools/ask-browserstack/stream.d.ts +0 -116
  42. package/dist/tools/ask-browserstack/stream.js +0 -236
  43. package/dist/tools/ask-browserstack/types.d.ts +0 -196
  44. package/dist/tools/ask-browserstack/types.js +0 -14
  45. package/dist/tools/tool-handoff.d.ts +0 -62
  46. package/dist/tools/tool-handoff.js +0 -75
@@ -0,0 +1,369 @@
1
+ /**
2
+ * Load the index artifact(s) and expose the lookups the tools need.
3
+ *
4
+ * ONE FILE PER PRODUCT is the released contract, so loading is a merge across files. The
5
+ * merged model keeps the products map the rest of the server already reads, which is what
6
+ * lets searchCapability rank across products from N single-product files.
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import { basename, dirname } from "node:path";
10
+ import { ENVELOPE_KEYS, SUPPORTED_SCHEMA_VERSION, } from "./types.js";
11
+ export class IndexError extends Error {
12
+ }
13
+ /** Thrown to the caller as a tool error, so the wording is caller-facing. */
14
+ export class InvocationError extends Error {
15
+ }
16
+ /** The file inside a product subdirectory, for the earlier nested layout. */
17
+ export const INDEX_FILE = "index.json";
18
+ /** The stored layout, and the name the export publishes: `<product>.capability-index.json`. */
19
+ export const FLAT_SUFFIX = ".capability-index.json";
20
+ /**
21
+ * The product a file's LOCATION claims to describe, if its layout says so.
22
+ *
23
+ * `capability/tm.capability-index.json` and `capability/tm/index.json` both name their
24
+ * product, and
25
+ * `fromFiles` cross-checks that against the product key inside. A file in the wrong place
26
+ * would otherwise register its product under the directory's name and answer for endpoints
27
+ * it does not have.
28
+ */
29
+ export function productFromPath(file) {
30
+ const base = basename(file);
31
+ if (base.endsWith(FLAT_SUFFIX))
32
+ return base.slice(0, -FLAT_SUFFIX.length);
33
+ if (base === INDEX_FILE)
34
+ return basename(dirname(file));
35
+ return undefined;
36
+ }
37
+ export function endpointKey(method, path) {
38
+ return `${(method || "").trim().toUpperCase()} ${(path || "").trim()}`;
39
+ }
40
+ function isPlainObject(value) {
41
+ return typeof value === "object" && value !== null && !Array.isArray(value);
42
+ }
43
+ /**
44
+ * Read one artifact file into the product it carries.
45
+ *
46
+ * SHAPE DETECTION, NOT VERSION DETECTION. The released envelope and the pre-release one
47
+ * both declare `schema_version: 1`, so the number cannot tell them apart; the `products`
48
+ * wrapper can, and is the documented discriminator. The pre-release branch is defensive
49
+ * only — that shape was never deployed.
50
+ */
51
+ export function readIndexFile(raw, source = "index") {
52
+ if (!isPlainObject(raw)) {
53
+ throw new IndexError(`${source}: expected a JSON object`);
54
+ }
55
+ if (raw.schema_version !== SUPPORTED_SCHEMA_VERSION) {
56
+ // Refuse rather than best-effort read: a shape change the generator announced is
57
+ // exactly the case where guessing produces silently wrong tool output.
58
+ throw new IndexError(`${source}: unsupported index schema_version ${raw.schema_version}; this build reads ` +
59
+ `${SUPPORTED_SCHEMA_VERSION}. Rebuild the artifact or update the server.`);
60
+ }
61
+ const provenance = {
62
+ build_id: typeof raw.build_id === "string" ? raw.build_id : "",
63
+ ...(typeof raw.version === "string" ? { version: raw.version } : {}),
64
+ };
65
+ if (isPlainObject(raw.products)) {
66
+ // Pre-release shape. Never deployed; recognised so a stray file reads rather than
67
+ // failing in a way that looks like a corrupt artifact.
68
+ const entries = Object.entries(raw.products);
69
+ if (entries.length === 0)
70
+ throw new IndexError(`${source}: contains no products`);
71
+ if (entries.length > 1) {
72
+ throw new IndexError(`${source}: carries ${entries.length} products; one file describes one product`);
73
+ }
74
+ const [name, product] = entries[0];
75
+ return {
76
+ name,
77
+ product: asProduct(product, `${source}:${name}`),
78
+ provenance,
79
+ };
80
+ }
81
+ // Released shape: exactly one key that is not part of the envelope.
82
+ const envelope = new Set(ENVELOPE_KEYS);
83
+ const entries = Object.entries(raw).filter(([key, value]) => !envelope.has(key) && isPlainObject(value));
84
+ if (entries.length === 0) {
85
+ throw new IndexError(`${source}: no product object found; expected one top-level key besides ` +
86
+ `${[...envelope].join(", ")}`);
87
+ }
88
+ if (entries.length > 1) {
89
+ throw new IndexError(`${source}: found ${entries.length} candidate product keys ` +
90
+ `(${entries
91
+ .map(([key]) => key)
92
+ .sort()
93
+ .join(", ")}); one file describes one product`);
94
+ }
95
+ const [name, product] = entries[0];
96
+ return { name, product: asProduct(product, `${source}:${name}`), provenance };
97
+ }
98
+ function asProduct(value, source) {
99
+ if (!isPlainObject(value) || !Array.isArray(value.capabilities)) {
100
+ throw new IndexError(`${source}: product object has no capabilities[]`);
101
+ }
102
+ return value;
103
+ }
104
+ export class CapabilityRegistry {
105
+ index;
106
+ /** product -> provenance of the file it came from. */
107
+ provenance;
108
+ /** product -> "METHOD /path" -> capability */
109
+ byEndpoint = new Map();
110
+ /** product -> capability name -> capability. Empty for products that publish no names. */
111
+ byName = new Map();
112
+ constructor(index, provenance = {}) {
113
+ if (index?.schema_version !== SUPPORTED_SCHEMA_VERSION) {
114
+ throw new IndexError(`unsupported index schema_version ${index?.schema_version}; this build reads ` +
115
+ `${SUPPORTED_SCHEMA_VERSION}. Rebuild the artifact or update the server.`);
116
+ }
117
+ if (!index.products || Object.keys(index.products).length === 0) {
118
+ throw new IndexError("index contains no products");
119
+ }
120
+ this.index = index;
121
+ this.provenance = provenance;
122
+ for (const [product, bundle] of Object.entries(index.products)) {
123
+ const lookup = new Map();
124
+ const names = new Map();
125
+ for (const capability of bundle.capabilities) {
126
+ lookup.set(endpointKey(capability.method, capability.path), capability);
127
+ if (!capability.name)
128
+ continue;
129
+ const clash = names.get(capability.name);
130
+ if (clash) {
131
+ // A duplicate name makes one of the two permanently unreachable, and which one
132
+ // wins would depend on array order. The export gates this, but a hand-edited or
133
+ // stale artifact must not load and then silently drop an endpoint.
134
+ throw new IndexError(`${product}: capability name '${capability.name}' is used by both ` +
135
+ `${endpointKey(clash.method, clash.path)} and ` +
136
+ `${endpointKey(capability.method, capability.path)}; names must be unique ` +
137
+ `within a product`);
138
+ }
139
+ names.set(capability.name, capability);
140
+ }
141
+ this.byEndpoint.set(product, lookup);
142
+ this.byName.set(product, names);
143
+ }
144
+ }
145
+ static fromFile(file) {
146
+ return CapabilityRegistry.fromFiles([file]);
147
+ }
148
+ /**
149
+ * Merge every discovered artifact into one registry.
150
+ *
151
+ * ANY unreadable file fails the whole load, deliberately. Skipping one and carrying on
152
+ * would leave a registry that answers "no such capability" for a product that exists —
153
+ * a confident wrong answer, which is worse than the caller-visible absence of the whole
154
+ * surface (which `register.ts` logs a reason for).
155
+ */
156
+ static fromFiles(files) {
157
+ if (files.length === 0)
158
+ throw new IndexError("no index files to load");
159
+ const products = {};
160
+ const provenance = {};
161
+ for (const file of files) {
162
+ let parsed;
163
+ try {
164
+ parsed = JSON.parse(readFileSync(file, "utf8"));
165
+ }
166
+ catch (error) {
167
+ throw new IndexError(`${file}: could not be read as JSON (${error instanceof Error ? error.message : String(error)})`);
168
+ }
169
+ const loaded = readIndexFile(parsed, file);
170
+ const claimed = productFromPath(file);
171
+ if (claimed && claimed !== loaded.name) {
172
+ // The name is stated twice — by the path and by the key inside — and they must
173
+ // agree. Trusting either one alone would serve a product's endpoints under the
174
+ // other's name, and every search result would then point at the wrong host.
175
+ throw new IndexError(`${file}: is stored as product '${claimed}' but declares '${loaded.name}'`);
176
+ }
177
+ if (products[loaded.name]) {
178
+ // Two files claiming one product cannot both be right, and picking one silently
179
+ // decides which endpoints exist.
180
+ throw new IndexError(`product '${loaded.name}' is declared by more than one index file; ${file} is a duplicate`);
181
+ }
182
+ products[loaded.name] = loaded.product;
183
+ provenance[loaded.name] = loaded.provenance;
184
+ }
185
+ return new CapabilityRegistry({
186
+ schema_version: SUPPORTED_SCHEMA_VERSION,
187
+ build_id: compositeBuildId(provenance),
188
+ products,
189
+ }, provenance);
190
+ }
191
+ /** The single product's build id, or `name:id` pairs when several are loaded. */
192
+ get buildId() {
193
+ return this.index.build_id;
194
+ }
195
+ productNames() {
196
+ return Object.keys(this.index.products).sort();
197
+ }
198
+ /** Per-product `{build_id, version}`, for logging and cache-busting only. */
199
+ buildInfo() {
200
+ return this.provenance;
201
+ }
202
+ /**
203
+ * Find a capability by its published name — the preferred handle.
204
+ *
205
+ * Names are unique within a product but not across products, so an ambiguous name is
206
+ * reported rather than resolved by load order. A name that exists in no index is
207
+ * `unknown_capability`: a distinct outcome from a name that exists elsewhere, because the
208
+ * caller's next move differs — search again, versus pass `product`.
209
+ */
210
+ byNameLookup(name, product) {
211
+ const matches = [];
212
+ for (const [owner, lookup] of this.byName) {
213
+ if (product && owner !== product)
214
+ continue;
215
+ const capability = lookup.get(name);
216
+ if (capability)
217
+ matches.push({ product: owner, capability });
218
+ }
219
+ if (matches.length === 0) {
220
+ // Say whether names are published at all for the product asked about: "no such name"
221
+ // and "this product does not name its capabilities" need different fixes.
222
+ const unnamed = [...this.byName]
223
+ .filter(([owner, lookup]) => (!product || owner === product) && lookup.size === 0)
224
+ .map(([owner]) => owner);
225
+ const hint = unnamed.length
226
+ ? ` ${unnamed.sort().join(", ")} ${unnamed.length > 1 ? "publish" : "publishes"} ` +
227
+ `no capability names yet — call those by \`method\` and \`path\` instead.`
228
+ : " Search again — names come from searchCapability and describeEntity.";
229
+ throw new InvocationError(`unknown_capability: ${name}.${hint}`);
230
+ }
231
+ if (matches.length > 1 && !product) {
232
+ const owners = matches
233
+ .map((m) => m.product)
234
+ .sort()
235
+ .join(", ");
236
+ throw new InvocationError(`capability name '${name}' exists in several products (${owners}); pass product`);
237
+ }
238
+ return matches[0];
239
+ }
240
+ /**
241
+ * Find a capability by the endpoint it exposes — the handle for unnamed products.
242
+ *
243
+ * The endpoint is what searchCapability returns, so it is the only thing a caller can
244
+ * hold. `unknown_endpoint` is a defined outcome rather than a generic failure: a caller
245
+ * working from stale search output needs to know to search again, not to retry.
246
+ */
247
+ byEndpointLookup(method, path, product) {
248
+ const key = endpointKey(method, path);
249
+ const matches = [];
250
+ for (const [name, lookup] of this.byEndpoint) {
251
+ if (product && name !== product)
252
+ continue;
253
+ const capability = lookup.get(key);
254
+ if (capability)
255
+ matches.push({ product: name, capability });
256
+ }
257
+ if (matches.length === 0) {
258
+ throw new InvocationError(`unknown_endpoint: ${key}. Search again — send \`method\` and \`path\` exactly as ` +
259
+ `searchCapability returned them, placeholders included.`);
260
+ }
261
+ if (matches.length > 1 && !product) {
262
+ const owners = matches
263
+ .map((m) => m.product)
264
+ .sort()
265
+ .join(", ");
266
+ throw new InvocationError(`${key} exists in several products (${owners}); pass product`);
267
+ }
268
+ return matches[0];
269
+ }
270
+ }
271
+ function compositeBuildId(provenance) {
272
+ const names = Object.keys(provenance).sort();
273
+ if (names.length === 1)
274
+ return provenance[names[0]].build_id;
275
+ return names.map((name) => `${name}:${provenance[name].build_id}`).join(" ");
276
+ }
277
+ /**
278
+ * Resolve a `{$response|$schema: "Name"}` reference against the product's lookup tables.
279
+ *
280
+ * ONE HOP. The named component it returns may itself contain references — 39 of tm's 53
281
+ * named responses do — so this is the primitive, not the whole job. Use `resolveResponses`
282
+ * to get a tree with nothing left to look up.
283
+ *
284
+ * A node that is not a reference is returned as-is, and an unresolvable name yields
285
+ * `undefined` rather than throwing: the tables are additive and their absence means "no
286
+ * response schema available".
287
+ */
288
+ export function resolveComponent(product, node) {
289
+ if (!node || typeof node !== "object")
290
+ return node;
291
+ const ref = node;
292
+ if (typeof ref.$response === "string") {
293
+ return product.responses?.[ref.$response];
294
+ }
295
+ if (typeof ref.$schema === "string") {
296
+ return product.schemas?.[ref.$schema];
297
+ }
298
+ return node;
299
+ }
300
+ /**
301
+ * Resolve every reference in a tree, however deep.
302
+ *
303
+ * REFERENCES ARE NESTED, which is the part a one-hop reader gets wrong. They appear at the
304
+ * top of a response (`{"$response": "BadRequest"}`), on its schema
305
+ * (`.../schema/{"$schema": "TestCaseListResponse"}`), and inside the schema's own
306
+ * properties (`.../schema/properties/data/properties/folder`). Chains are real too: a
307
+ * capability's 400 resolves to the named `BadRequest`, whose schema is `{"$schema":
308
+ * "ErrorResponse"}`.
309
+ *
310
+ * AN UNRESOLVABLE REFERENCE IS LEFT IN PLACE, not dropped and not thrown on. A dangling
311
+ * name (the tables are built separately from the capabilities) or a cycle (a folder whose
312
+ * schema contains folders) then shows up as the `{"$schema": "…"}` node it is, which a
313
+ * reader can still act on, rather than as a silently truncated schema.
314
+ */
315
+ export function resolveDeep(product, node) {
316
+ return resolveNode(product, node, new Set());
317
+ }
318
+ function resolveNode(product, node, seen) {
319
+ if (Array.isArray(node)) {
320
+ return node.map((item) => resolveNode(product, item, seen));
321
+ }
322
+ if (typeof node !== "object" || node === null)
323
+ return node;
324
+ const ref = node;
325
+ const kind = typeof ref.$response === "string"
326
+ ? "$response"
327
+ : typeof ref.$schema === "string"
328
+ ? "$schema"
329
+ : undefined;
330
+ if (kind) {
331
+ const name = (kind === "$response" ? ref.$response : ref.$schema);
332
+ const key = `${kind}:${name}`;
333
+ const target = kind === "$response"
334
+ ? product.responses?.[name]
335
+ : product.schemas?.[name];
336
+ // Leave the reference visible when it cannot be followed, or when following it would
337
+ // revisit a name already on this path.
338
+ if (!target || seen.has(key))
339
+ return node;
340
+ return resolveNode(product, target, new Set([...seen, key]));
341
+ }
342
+ const out = {};
343
+ for (const [field, value] of Object.entries(node)) {
344
+ out[field] = resolveNode(product, value, seen);
345
+ }
346
+ return out;
347
+ }
348
+ /**
349
+ * A capability's declared responses with every reference followed.
350
+ *
351
+ * SUCCESS ONLY BY DEFAULT. The error entries are near-identical across the surface — 148 of
352
+ * 173 capabilities declare the same `InternalServerError`, and all of them bottom out in
353
+ * one `ErrorResponse` schema — so including them multiplies a search payload by 6.4x to
354
+ * repeat boilerplate the caller learns from the actual failure anyway. The 2xx entry is the
355
+ * one that says what a successful call returns, which is what a caller needs BEFORE calling.
356
+ *
357
+ * Returns undefined when the capability declares none — which is every capability in an
358
+ * index built before the response tables were added, and is not an error.
359
+ */
360
+ export function resolveResponses(product, capability, selection = "success") {
361
+ if (selection === "none" || !capability.responses)
362
+ return undefined;
363
+ const wanted = selection === "all"
364
+ ? Object.entries(capability.responses)
365
+ : Object.entries(capability.responses).filter(([status]) => status.startsWith("2"));
366
+ if (wanted.length === 0)
367
+ return undefined;
368
+ return resolveDeep(product, Object.fromEntries(wanted));
369
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The tool surface: four discovery tools plus ONE invoke tool.
3
+ *
4
+ * ONE invoke tool means one set of MCP annotations, so they describe the whole surface
5
+ * honestly: it can write (not read-only) and it can never delete, because destructive
6
+ * endpoints are refused before binding. Write consent therefore rests on `user_permission`
7
+ * enforced HERE rather than on a client-side hint — which is the one thing a separate
8
+ * read/write tool pair was buying.
9
+ */
10
+ import { McpServer, RegisteredTool } from "@modelcontextprotocol/sdk/server/mcp.js";
11
+ import { BrowserStackConfig } from "../../lib/types.js";
12
+ import { Credentials, Transport } from "./egress.js";
13
+ import { CapabilityRegistry } from "./index-loader.js";
14
+ export declare const PERMISSION_VALUES: readonly ["not_asked", "granted", "denied"];
15
+ export interface RegistryDeps {
16
+ registry: CapabilityRegistry;
17
+ /**
18
+ * Per-product base URL. Never baked into the artifact — it is environment AND account
19
+ * specific: tm is region-sharded, so this is resolved per call, not once at startup.
20
+ */
21
+ baseUrlFor: (product: string) => Promise<string>;
22
+ credentialsFor: () => Credentials;
23
+ transport?: Transport;
24
+ }
25
+ /**
26
+ * The tool-adder the server factory calls.
27
+ *
28
+ * Registers NOTHING when the artifact is absent or unreadable, rather than throwing: a
29
+ * missing index is a packaging problem, and taking the whole MCP server down with it would
30
+ * remove every other product's tools too. The reason is logged so it is not silent.
31
+ */
32
+ export declare function addCapabilityRegistryToolsFromConfig(server: McpServer, config: BrowserStackConfig): Record<string, RegisteredTool>;
33
+ export declare function addCapabilityRegistryTools(server: McpServer, deps: RegistryDeps, config?: BrowserStackConfig): Record<string, RegisteredTool>;
34
+ export default addCapabilityRegistryToolsFromConfig;