@browserstack/mcp-server 1.5.0-beta.21 → 1.5.0-beta.22

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 (95) hide show
  1. package/README.md +32 -48
  2. package/capability/loadtesting.capability-index.json +1876 -0
  3. package/capability/tm.capability-index.json +50104 -0
  4. package/dist/config.d.ts +1 -4
  5. package/dist/config.js +2 -23
  6. package/dist/index.d.ts +1 -2
  7. package/dist/index.js +3 -7
  8. package/dist/lib/constants.d.ts +0 -3
  9. package/dist/lib/constants.js +0 -3
  10. package/dist/lib/instrumentation.d.ts +2 -14
  11. package/dist/lib/instrumentation.js +29 -104
  12. package/dist/lib/upload-validator.d.ts +2 -3
  13. package/dist/lib/upload-validator.js +15 -18
  14. package/dist/lib/utils.js +3 -10
  15. package/dist/lib/version-resolver.d.ts +5 -0
  16. package/dist/lib/version-resolver.js +2 -8
  17. package/dist/logger.js +10 -1
  18. package/dist/server-factory.js +6 -10
  19. package/dist/tools/accessibility.js +5 -9
  20. package/dist/tools/accessiblity-utils/accessibility-rag.js +1 -3
  21. package/dist/tools/appautomate-utils/native-execution/constants.js +2 -4
  22. package/dist/tools/appautomate.js +1 -3
  23. package/dist/tools/applive.js +1 -1
  24. package/dist/tools/automate.d.ts +0 -7
  25. package/dist/tools/automate.js +1 -104
  26. package/dist/tools/bstack-sdk.js +2 -2
  27. package/dist/tools/build-insights.js +2 -41
  28. package/dist/tools/capability-registry/bind.d.ts +29 -0
  29. package/dist/tools/capability-registry/bind.js +329 -0
  30. package/dist/tools/capability-registry/config.d.ts +62 -0
  31. package/dist/tools/capability-registry/config.js +218 -0
  32. package/dist/tools/capability-registry/discovery.d.ts +44 -0
  33. package/dist/tools/capability-registry/discovery.js +99 -0
  34. package/dist/tools/capability-registry/egress.d.ts +44 -0
  35. package/dist/tools/capability-registry/egress.js +174 -0
  36. package/dist/tools/capability-registry/index-loader.d.ts +133 -0
  37. package/dist/tools/capability-registry/index-loader.js +404 -0
  38. package/dist/tools/capability-registry/register.d.ts +48 -0
  39. package/dist/tools/capability-registry/register.js +604 -0
  40. package/dist/tools/capability-registry/resolve.d.ts +38 -0
  41. package/dist/tools/capability-registry/resolve.js +45 -0
  42. package/dist/tools/capability-registry/search.d.ts +170 -0
  43. package/dist/tools/capability-registry/search.js +709 -0
  44. package/dist/tools/capability-registry/types.d.ts +282 -0
  45. package/dist/tools/capability-registry/types.js +33 -0
  46. package/dist/tools/failurelogs-utils/app-automate.js +3 -4
  47. package/dist/tools/failurelogs-utils/automate.js +4 -5
  48. package/dist/tools/get-failure-logs.js +11 -30
  49. package/dist/tools/observability.js +1 -3
  50. package/dist/tools/percy-sdk.js +9 -9
  51. package/dist/tools/rca-agent-utils/format-rca.js +4 -5
  52. package/dist/tools/rca-agent-utils/get-failed-test-id.js +0 -12
  53. package/dist/tools/rca-agent-utils/types.d.ts +0 -1
  54. package/dist/tools/rca-agent.js +2 -5
  55. package/dist/tools/review-agent.js +1 -2
  56. package/dist/tools/sdk-utils/common/constants.d.ts +1 -1
  57. package/dist/tools/sdk-utils/common/constants.js +1 -2
  58. package/dist/tools/selfheal.js +3 -6
  59. package/dist/tools/testmanagement-utils/TCG-utils/api.js +7 -26
  60. package/dist/tools/testmanagement-utils/TCG-utils/config.d.ts +0 -2
  61. package/dist/tools/testmanagement-utils/TCG-utils/config.js +0 -5
  62. package/dist/tools/testmanagement-utils/testcase-from-file.js +1 -2
  63. package/dist/tools/testmanagement-utils/upload-file.js +2 -16
  64. package/dist/tools/testmanagement.js +17 -39
  65. package/package.json +11 -5
  66. package/dist/lib/node-version-notice.d.ts +0 -1
  67. package/dist/lib/node-version-notice.js +0 -9
  68. package/dist/lib/tool-latency.d.ts +0 -4
  69. package/dist/lib/tool-latency.js +0 -16
  70. package/dist/lib/untrusted-content.d.ts +0 -15
  71. package/dist/lib/untrusted-content.js +0 -24
  72. package/dist/tools/ask-browserstack/central-oauth.d.ts +0 -120
  73. package/dist/tools/ask-browserstack/central-oauth.js +0 -277
  74. package/dist/tools/ask-browserstack/config.d.ts +0 -102
  75. package/dist/tools/ask-browserstack/config.js +0 -140
  76. package/dist/tools/ask-browserstack/egress.d.ts +0 -34
  77. package/dist/tools/ask-browserstack/egress.js +0 -31
  78. package/dist/tools/ask-browserstack/register.d.ts +0 -61
  79. package/dist/tools/ask-browserstack/register.js +0 -416
  80. package/dist/tools/ask-browserstack/relay.d.ts +0 -201
  81. package/dist/tools/ask-browserstack/relay.js +0 -577
  82. package/dist/tools/ask-browserstack/stream.d.ts +0 -116
  83. package/dist/tools/ask-browserstack/stream.js +0 -236
  84. package/dist/tools/ask-browserstack/types.d.ts +0 -196
  85. package/dist/tools/ask-browserstack/types.js +0 -14
  86. package/dist/tools/automate-utils/list-session-ids.d.ts +0 -28
  87. package/dist/tools/automate-utils/list-session-ids.js +0 -87
  88. package/dist/tools/automate-utils/resolve-hashed-build-id.d.ts +0 -30
  89. package/dist/tools/automate-utils/resolve-hashed-build-id.js +0 -124
  90. package/dist/tools/failurelogs-utils/resolve-app-build-id.d.ts +0 -2
  91. package/dist/tools/failurelogs-utils/resolve-app-build-id.js +0 -5
  92. package/dist/tools/failurelogs-utils/video.d.ts +0 -3
  93. package/dist/tools/failurelogs-utils/video.js +0 -25
  94. package/dist/tools/tool-handoff.d.ts +0 -66
  95. package/dist/tools/tool-handoff.js +0 -78
@@ -0,0 +1,133 @@
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 { Capability, ProductIndex, Provenance, RegistryIndex, ResponseDoc, SchemaNode } from "./types.js";
9
+ export declare class IndexError extends Error {
10
+ }
11
+ /** Thrown to the caller as a tool error, so the wording is caller-facing. */
12
+ export declare class InvocationError extends Error {
13
+ }
14
+ /** The file inside a product subdirectory, for the earlier nested layout. */
15
+ export declare const INDEX_FILE = "index.json";
16
+ /** The stored layout, and the name the export publishes: `<product>.capability-index.json`. */
17
+ export declare const FLAT_SUFFIX = ".capability-index.json";
18
+ /**
19
+ * The product a file's LOCATION claims to describe, if its layout says so.
20
+ *
21
+ * `capability/tm.capability-index.json` and `capability/tm/index.json` both name their
22
+ * product, and
23
+ * `fromFiles` cross-checks that against the product key inside. A file in the wrong place
24
+ * would otherwise register its product under the directory's name and answer for endpoints
25
+ * it does not have.
26
+ */
27
+ export declare function productFromPath(file: string): string | undefined;
28
+ export declare function endpointKey(method: string, path: string): string;
29
+ export interface LoadedProduct {
30
+ name: string;
31
+ product: ProductIndex;
32
+ provenance: Provenance;
33
+ }
34
+ /**
35
+ * Read one artifact file into the product it carries.
36
+ *
37
+ * SHAPE DETECTION, NOT VERSION DETECTION. The released envelope and the pre-release one
38
+ * both declare `schema_version: 1`, so the number cannot tell them apart; the `products`
39
+ * wrapper can, and is the documented discriminator. The pre-release branch is defensive
40
+ * only — that shape was never deployed.
41
+ */
42
+ export declare function readIndexFile(raw: unknown, source?: string): LoadedProduct;
43
+ export declare class CapabilityRegistry {
44
+ readonly index: RegistryIndex;
45
+ /** product -> provenance of the file it came from. */
46
+ readonly provenance: Record<string, Provenance>;
47
+ /** product -> "METHOD /path" -> capability */
48
+ private readonly byEndpoint;
49
+ /** product -> capability name -> capability. Empty for products that publish no names. */
50
+ private readonly byName;
51
+ constructor(index: RegistryIndex, provenance?: Record<string, Provenance>);
52
+ static fromFile(file: string): CapabilityRegistry;
53
+ /**
54
+ * Merge every discovered artifact into one registry.
55
+ *
56
+ * ANY unreadable file fails the whole load, deliberately. Skipping one and carrying on
57
+ * would leave a registry that answers "no such capability" for a product that exists —
58
+ * a confident wrong answer, which is worse than the caller-visible absence of the whole
59
+ * surface (which `register.ts` logs a reason for).
60
+ */
61
+ static fromFiles(files: string[]): CapabilityRegistry;
62
+ /** The single product's build id, or `name:id` pairs when several are loaded. */
63
+ get buildId(): string;
64
+ productNames(): string[];
65
+ /** Per-product `{build_id, version}`, for logging and cache-busting only. */
66
+ buildInfo(): Record<string, Provenance>;
67
+ /**
68
+ * Find a capability by its published name — the preferred handle.
69
+ *
70
+ * Names are unique within a product but not across products, so an ambiguous name is
71
+ * reported rather than resolved by load order. A name that exists in no index is
72
+ * `unknown_capability`: a distinct outcome from a name that exists elsewhere, because the
73
+ * caller's next move differs — search again, versus pass `product`.
74
+ */
75
+ byNameLookup(name: string, product?: string): {
76
+ product: string;
77
+ capability: Capability;
78
+ };
79
+ /**
80
+ * Find a capability by the endpoint it exposes — the handle for unnamed products.
81
+ *
82
+ * The endpoint is what searchCapability returns, so it is the only thing a caller can
83
+ * hold. `unknown_endpoint` is a defined outcome rather than a generic failure: a caller
84
+ * working from stale search output needs to know to search again, not to retry.
85
+ */
86
+ byEndpointLookup(method: string, path: string, product?: string): {
87
+ product: string;
88
+ capability: Capability;
89
+ };
90
+ }
91
+ /**
92
+ * Resolve a `{$response|$schema: "Name"}` reference against the product's lookup tables.
93
+ *
94
+ * ONE HOP. The named component it returns may itself contain references — 39 of tm's 53
95
+ * named responses do — so this is the primitive, not the whole job. Use `resolveResponses`
96
+ * to get a tree with nothing left to look up.
97
+ *
98
+ * A node that is not a reference is returned as-is, and an unresolvable name yields
99
+ * `undefined` rather than throwing: the tables are additive and their absence means "no
100
+ * response schema available".
101
+ */
102
+ export declare function resolveComponent<T extends ResponseDoc | SchemaNode>(product: ProductIndex, node: T | undefined): T | undefined;
103
+ /**
104
+ * Resolve every reference in a tree, however deep.
105
+ *
106
+ * REFERENCES ARE NESTED, which is the part a one-hop reader gets wrong. They appear at the
107
+ * top of a response (`{"$response": "BadRequest"}`), on its schema
108
+ * (`.../schema/{"$schema": "TestCaseListResponse"}`), and inside the schema's own
109
+ * properties (`.../schema/properties/data/properties/folder`). Chains are real too: a
110
+ * capability's 400 resolves to the named `BadRequest`, whose schema is `{"$schema":
111
+ * "ErrorResponse"}`.
112
+ *
113
+ * AN UNRESOLVABLE REFERENCE IS LEFT IN PLACE, not dropped and not thrown on. A dangling
114
+ * name (the tables are built separately from the capabilities) or a cycle (a folder whose
115
+ * schema contains folders) then shows up as the `{"$schema": "…"}` node it is, which a
116
+ * reader can still act on, rather than as a silently truncated schema.
117
+ */
118
+ export declare function resolveDeep<T>(product: ProductIndex, node: T): T;
119
+ /** Which declared responses to hand back. */
120
+ export type ResponseSelection = "success" | "all" | "none";
121
+ /**
122
+ * A capability's declared responses with every reference followed.
123
+ *
124
+ * SUCCESS ONLY BY DEFAULT. The error entries are near-identical across the surface — 148 of
125
+ * 173 capabilities declare the same `InternalServerError`, and all of them bottom out in
126
+ * one `ErrorResponse` schema — so including them multiplies a search payload by 6.4x to
127
+ * repeat boilerplate the caller learns from the actual failure anyway. The 2xx entry is the
128
+ * one that says what a successful call returns, which is what a caller needs BEFORE calling.
129
+ *
130
+ * Returns undefined when the capability declares none — which is every capability in an
131
+ * index built before the response tables were added, and is not an error.
132
+ */
133
+ export declare function resolveResponses(product: ProductIndex, capability: Capability, selection?: ResponseSelection): Record<string, ResponseDoc> | undefined;
@@ -0,0 +1,404 @@
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
+ const resolved = resolveNode(product, target, new Set([...seen, key]));
341
+ // KEYS WRITTEN BESIDE THE REF SURVIVE IT, AND WIN.
342
+ //
343
+ // This used to return the target and drop every sibling, which silently ate 16 nodes
344
+ // in the shipped tm index: 14 authored descriptions and two `nullable: true` flags.
345
+ // The losses are exactly the caveats hardest to rediscover — "only when no step
346
+ // results were submitted", "Present only on root-folder creation", and a `nullable`
347
+ // marking the one field that comes back NULL when a search fails, which is the
348
+ // absent-versus-explicitly-null distinction a caller cannot otherwise make.
349
+ //
350
+ // It also cost real work downstream. A live probe reported one of those caveats as a
351
+ // missing conditional and it had been written all along — this resolver removed it
352
+ // between the author and the caller. Worse, the product team began splitting shared
353
+ // schemas so a caveat would have somewhere to live that survived, trading a lost
354
+ // sentence for two descriptions of one serializer that then drift apart.
355
+ //
356
+ // SIBLINGS WIN over the resolved target, not the reverse. A description written at the
357
+ // reference site is about THAT usage — "only when no step results were submitted" is
358
+ // true of one consumer of TestResult, not of TestResult everywhere — which is the
359
+ // whole reason it was written beside the ref instead of on the schema.
360
+ const siblings = {};
361
+ for (const [field, value] of Object.entries(node)) {
362
+ if (field !== "$schema" && field !== "$response")
363
+ siblings[field] = value;
364
+ }
365
+ if (Object.keys(siblings).length === 0)
366
+ return resolved;
367
+ if (typeof resolved !== "object" ||
368
+ resolved === null ||
369
+ Array.isArray(resolved)) {
370
+ return resolved;
371
+ }
372
+ return {
373
+ ...resolved,
374
+ ...resolveNode(product, siblings, seen),
375
+ };
376
+ }
377
+ const out = {};
378
+ for (const [field, value] of Object.entries(node)) {
379
+ out[field] = resolveNode(product, value, seen);
380
+ }
381
+ return out;
382
+ }
383
+ /**
384
+ * A capability's declared responses with every reference followed.
385
+ *
386
+ * SUCCESS ONLY BY DEFAULT. The error entries are near-identical across the surface — 148 of
387
+ * 173 capabilities declare the same `InternalServerError`, and all of them bottom out in
388
+ * one `ErrorResponse` schema — so including them multiplies a search payload by 6.4x to
389
+ * repeat boilerplate the caller learns from the actual failure anyway. The 2xx entry is the
390
+ * one that says what a successful call returns, which is what a caller needs BEFORE calling.
391
+ *
392
+ * Returns undefined when the capability declares none — which is every capability in an
393
+ * index built before the response tables were added, and is not an error.
394
+ */
395
+ export function resolveResponses(product, capability, selection = "success") {
396
+ if (selection === "none" || !capability.responses)
397
+ return undefined;
398
+ const wanted = selection === "all"
399
+ ? Object.entries(capability.responses)
400
+ : Object.entries(capability.responses).filter(([status]) => status.startsWith("2"));
401
+ if (wanted.length === 0)
402
+ return undefined;
403
+ return resolveDeep(product, Object.fromEntries(wanted));
404
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The tool surface: four discovery tools plus ONE invoke tool.
3
+ *
4
+ * Discovery is deliberately two steps. `searchCapability` returns a shortlist — enough to
5
+ * CHOOSE — and `describeCapability` returns the contract for the one chosen. Parameters and
6
+ * response shapes are 86% of a full record and are needed once, not eight times: measured
7
+ * over eight queries, ~8.6k tokens a search becomes ~1.1k, and even describing every result
8
+ * still costs less than the single fat call did.
9
+ *
10
+ * ONE invoke tool means one set of MCP annotations, so they describe the whole surface
11
+ * honestly: it can write (not read-only) and it can never delete, because destructive
12
+ * endpoints are refused before binding. Write consent therefore rests on `user_permission`
13
+ * enforced HERE rather than on a client-side hint — which is the one thing a separate
14
+ * read/write tool pair was buying.
15
+ */
16
+ import { McpServer, RegisteredTool } from "@modelcontextprotocol/sdk/server/mcp.js";
17
+ import { BrowserStackConfig } from "../../lib/types.js";
18
+ import { Credentials, Transport } from "./egress.js";
19
+ import { CapabilityRegistry } from "./index-loader.js";
20
+ export declare const PERMISSION_VALUES: readonly ["not_asked", "granted", "denied"];
21
+ /**
22
+ * The search-side twin of `user_permission`: did a human choose the product, or did you?
23
+ *
24
+ * No `denied`. A refused write is a thing the caller must not do; a refused product choice
25
+ * is not a state — the user either named one, in which case you search it, or has not been
26
+ * asked, in which case there is nothing to search yet.
27
+ */
28
+ export declare const PRODUCT_CHOICE_VALUES: readonly ["not_asked", "user_confirmed"];
29
+ export interface RegistryDeps {
30
+ registry: CapabilityRegistry;
31
+ /**
32
+ * Per-product base URL. Never baked into the artifact — it is environment AND account
33
+ * specific: tm is region-sharded, so this is resolved per call, not once at startup.
34
+ */
35
+ baseUrlFor: (product: string) => Promise<string>;
36
+ credentialsFor: () => Credentials;
37
+ transport?: Transport;
38
+ }
39
+ /**
40
+ * The tool-adder the server factory calls.
41
+ *
42
+ * Registers NOTHING when the artifact is absent or unreadable, rather than throwing: a
43
+ * missing index is a packaging problem, and taking the whole MCP server down with it would
44
+ * remove every other product's tools too. The reason is logged so it is not silent.
45
+ */
46
+ export declare function addCapabilityRegistryToolsFromConfig(server: McpServer, config: BrowserStackConfig): Record<string, RegisteredTool>;
47
+ export declare function addCapabilityRegistryTools(server: McpServer, deps: RegistryDeps, config?: BrowserStackConfig): Record<string, RegisteredTool>;
48
+ export default addCapabilityRegistryToolsFromConfig;