mcp-browser-dev-tools 0.2.2 → 0.3.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.
- package/README.md +17 -15
- package/package.json +8 -2
- package/src/action-changes.mjs +340 -0
- package/src/browser-adapter.mjs +40 -4
- package/src/cdp-client.mjs +923 -43
- package/src/config.mjs +9 -0
- package/src/firefox-bidi-client.mjs +757 -47
- package/src/json-schema.mjs +14 -1
- package/src/mcp-server.mjs +59 -8
- package/src/network-control.mjs +156 -0
- package/src/page-context.mjs +306 -2
- package/src/page-script.mjs +1175 -13
- package/src/run-steps.mjs +75 -23
- package/src/run-tabs.mjs +11 -16
- package/src/screenshot-output.mjs +92 -1
- package/src/session-events.mjs +57 -0
- package/src/tool-schemas.mjs +88 -83
- package/src/tool-sets.mjs +73 -0
- package/src/tools/action-tools.mjs +217 -77
- package/src/tools/browser-tools.mjs +12 -19
- package/src/tools/inspection-tools.mjs +88 -54
- package/src/tools/more-tools.mjs +108 -0
- package/src/tools/performance-tools.mjs +116 -0
- package/src/tools/state-tools.mjs +62 -16
- package/src/upload-files.mjs +57 -0
package/src/json-schema.mjs
CHANGED
|
@@ -14,10 +14,16 @@ export function validateValue(path, value, schema) {
|
|
|
14
14
|
|
|
15
15
|
if (schema.additionalProperties === false) {
|
|
16
16
|
for (const key of Object.keys(value)) {
|
|
17
|
-
if (!(key
|
|
17
|
+
if (!Object.hasOwn(properties, key)) {
|
|
18
18
|
throw new Error(`${path}.${key} is not allowed`);
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
+
} else if (typeof schema.additionalProperties === "object") {
|
|
22
|
+
for (const [key, item] of Object.entries(value)) {
|
|
23
|
+
if (!Object.hasOwn(properties, key)) {
|
|
24
|
+
validateValue(`${path}.${key}`, item, schema.additionalProperties);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
21
27
|
}
|
|
22
28
|
|
|
23
29
|
for (const [key, propertySchema] of Object.entries(properties)) {
|
|
@@ -95,5 +101,12 @@ export function validateValue(path, value, schema) {
|
|
|
95
101
|
if (schema.minimum !== undefined && value < schema.minimum) {
|
|
96
102
|
throw new Error(`${path} must be >= ${schema.minimum}`);
|
|
97
103
|
}
|
|
104
|
+
|
|
105
|
+
if (
|
|
106
|
+
schema.exclusiveMinimum !== undefined &&
|
|
107
|
+
value <= schema.exclusiveMinimum
|
|
108
|
+
) {
|
|
109
|
+
throw new Error(`${path} must be > ${schema.exclusiveMinimum}`);
|
|
110
|
+
}
|
|
98
111
|
}
|
|
99
112
|
}
|
package/src/mcp-server.mjs
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import { ChangeTracker } from "./action-changes.mjs";
|
|
1
2
|
import { actionTools } from "./tools/action-tools.mjs";
|
|
2
3
|
import { browserTools } from "./tools/browser-tools.mjs";
|
|
3
4
|
import { inspectionTools } from "./tools/inspection-tools.mjs";
|
|
5
|
+
import { moreToolsTool } from "./tools/more-tools.mjs";
|
|
6
|
+
import { performanceTools } from "./tools/performance-tools.mjs";
|
|
4
7
|
import { stateTools } from "./tools/state-tools.mjs";
|
|
5
8
|
import { appendFile } from "node:fs/promises";
|
|
6
9
|
import { launchBrowser as launchLocalBrowser } from "./browser-launch-service.mjs";
|
|
@@ -13,6 +16,7 @@ import { validateValue } from "./json-schema.mjs";
|
|
|
13
16
|
import { createLogger } from "./logger.mjs";
|
|
14
17
|
import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
|
|
15
18
|
import { StepRunner, runStepsTool, stepSchema } from "./run-steps.mjs";
|
|
19
|
+
import { TOOL_GROUPS } from "./tool-sets.mjs";
|
|
16
20
|
import { TabRunner, runTabsTool } from "./run-tabs.mjs";
|
|
17
21
|
import { asToolResult } from "./tool-results.mjs";
|
|
18
22
|
|
|
@@ -67,6 +71,28 @@ const STATUS_PROBE_ATTEMPTS = 3;
|
|
|
67
71
|
|
|
68
72
|
const LAUNCH_GRACE_MS = 30_000;
|
|
69
73
|
|
|
74
|
+
// The definition clients see: additionalProperties: false tells a model
|
|
75
|
+
// nothing it acts on, so it is left out of what every turn pays for. Calls
|
|
76
|
+
// are still validated against the full schema.
|
|
77
|
+
function advertisedDefinition(definition) {
|
|
78
|
+
const strip = (value) => {
|
|
79
|
+
if (Array.isArray(value)) {
|
|
80
|
+
return value.map(strip);
|
|
81
|
+
}
|
|
82
|
+
if (!value || typeof value !== "object") {
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
return Object.fromEntries(
|
|
86
|
+
Object.entries(value)
|
|
87
|
+
.filter(
|
|
88
|
+
([key, item]) => !(key === "additionalProperties" && item === false),
|
|
89
|
+
)
|
|
90
|
+
.map(([key, item]) => [key, strip(item)]),
|
|
91
|
+
);
|
|
92
|
+
};
|
|
93
|
+
return strip(definition);
|
|
94
|
+
}
|
|
95
|
+
|
|
70
96
|
function sleep(ms) {
|
|
71
97
|
return new Promise((resolve) => {
|
|
72
98
|
setTimeout(resolve, ms);
|
|
@@ -219,25 +245,37 @@ export class McpBrowserDevToolsServer {
|
|
|
219
245
|
}
|
|
220
246
|
|
|
221
247
|
createTools() {
|
|
222
|
-
|
|
248
|
+
this.changeTracker = new ChangeTracker(this.browserAdapter);
|
|
249
|
+
// config.tools is the set listed to clients (null for all). The others
|
|
250
|
+
// stay reachable through more_tools and as run_steps and run_tabs
|
|
251
|
+
// steps, which can use every session tool.
|
|
252
|
+
const enabled = this.config.tools;
|
|
253
|
+
const all = [
|
|
223
254
|
...browserTools(this),
|
|
224
255
|
...stateTools(this),
|
|
225
256
|
...actionTools(this),
|
|
226
257
|
...inspectionTools(this),
|
|
258
|
+
...performanceTools(this),
|
|
227
259
|
];
|
|
260
|
+
const tools = all.filter(([name]) => !enabled || enabled.has(name));
|
|
261
|
+
const hidden = new Map(
|
|
262
|
+
all.filter(([name]) => enabled && !enabled.has(name)),
|
|
263
|
+
);
|
|
264
|
+
this.stepToolMap = new Map(all);
|
|
228
265
|
|
|
229
|
-
const stepTools =
|
|
266
|
+
const stepTools = all
|
|
230
267
|
.filter(([, tool]) =>
|
|
231
268
|
tool.definition.inputSchema.required?.includes("sessionId"),
|
|
232
269
|
)
|
|
233
270
|
.map(([name]) => name);
|
|
234
271
|
this.stepRunner = new StepRunner({
|
|
235
|
-
getTools: () => this.
|
|
272
|
+
getTools: () => this.stepToolMap,
|
|
236
273
|
browserAdapter: this.browserAdapter,
|
|
274
|
+
changeTracker: this.changeTracker,
|
|
237
275
|
stepSchema: stepSchema(stepTools),
|
|
238
276
|
conditionOptions: { expression: this.config.enableEvaluate },
|
|
239
277
|
});
|
|
240
|
-
tools.push(runStepsTool(this.stepRunner
|
|
278
|
+
tools.push(runStepsTool(this.stepRunner));
|
|
241
279
|
this.tabRunner = new TabRunner({
|
|
242
280
|
stepRunner: this.stepRunner,
|
|
243
281
|
browserAdapter: this.browserAdapter,
|
|
@@ -245,6 +283,9 @@ export class McpBrowserDevToolsServer {
|
|
|
245
283
|
tools.push(
|
|
246
284
|
runTabsTool(this.tabRunner, stepTools, this.config.browserFamily),
|
|
247
285
|
);
|
|
286
|
+
if (hidden.size > 0) {
|
|
287
|
+
tools.push(moreToolsTool(hidden, advertisedDefinition));
|
|
288
|
+
}
|
|
248
289
|
|
|
249
290
|
return new Map(tools);
|
|
250
291
|
}
|
|
@@ -331,8 +372,7 @@ export class McpBrowserDevToolsServer {
|
|
|
331
372
|
name: SERVER_NAME,
|
|
332
373
|
version: SERVER_VERSION,
|
|
333
374
|
},
|
|
334
|
-
instructions:
|
|
335
|
-
'Use the browser tools to inspect tabs, console output, network activity, DOM structure, element state, screenshots, and page interactions across Chromium CDP or Firefox BiDi. To act on a page and check the result, prefer run_steps: send the actions you already know (such as every field of a form), a wait_for, and the check (take_screenshot with output image, or inspect_element) in one call instead of several round trips, for example {"sessionId":"<id>","steps":[{"tool":"type","arguments":{"selector":"#search","text":"headphones"}},{"tool":"press_key","arguments":{"key":"Enter"}},{"tool":"wait_for","arguments":{"selector":"#results"}},{"tool":"take_screenshot","arguments":{"output":"image"}}]}. Add an if step when the page can be in more than one state. To read several pages, open them together with run_tabs and read each with read_text. Locators: plain CSS (or css=) takes the first match; text=Foo takes the first visible element whose text equals Foo, else contains it, in document order, so it can match a wrapper; role=button[name="Save"] matches ARIA role and accessible name (equal or containing) without a visibility check; name=Foo takes the first visible element whose accessible name equals or contains Foo, and a matched <label> resolves to its control when that control is visible. Comparisons are case-sensitive; iframes and shadow roots are not searched.',
|
|
375
|
+
instructions: `Browser tools for Chromium (CDP) and Firefox (BiDi). Call attach_tab first; tools that take sessionId use the one it returns. To see a page, call get_snapshot: one line per visible heading and control (iframes too), each with a ref such as e12 or f1e3, far cheaper than a screenshot. To act, prefer run_steps: send the actions you already know, such as every field of a form, in one call: {"sessionId":"<id>","steps":[{"tool":"type","arguments":{"selector":"ref=e3","text":"Ada"}},{"tool":"click","arguments":{"selector":"ref=e4"}}]}. Actions return changes once the page settles: controls added, removed, or updated, new text such as an error or a toast, URL and title, console errors, and after a navigation the new page's snapshot. That is usually the check; add wait_for only for something later. Read several pages at once with run_tabs and read_text. Locators: ref=e12 is a get_snapshot element, until the page navigates; plain CSS (or css=) takes the first match; text=Foo the first visible element whose text equals, else contains, Foo; role=button[name="Save"] matches role and accessible name; name=Foo the first visible element whose accessible name equals or contains Foo (a label resolves to its control). Matching is case-sensitive; only refs reach into iframes. x and y are viewport CSS pixels; a screenshot's cssRect and scale convert image pixels. more_tools lists the tools not listed here (drag, cookies, request mocking, HAR, performance) and calls them; they also work as run_steps steps.`,
|
|
336
376
|
});
|
|
337
377
|
case "notifications/initialized":
|
|
338
378
|
return null;
|
|
@@ -340,7 +380,9 @@ export class McpBrowserDevToolsServer {
|
|
|
340
380
|
return success(id, {});
|
|
341
381
|
case "tools/list":
|
|
342
382
|
return success(id, {
|
|
343
|
-
tools: Array.from(this.tools.values(), (tool) =>
|
|
383
|
+
tools: Array.from(this.tools.values(), (tool) =>
|
|
384
|
+
advertisedDefinition(tool.definition),
|
|
385
|
+
),
|
|
344
386
|
});
|
|
345
387
|
case "tools/call":
|
|
346
388
|
return success(id, await this.callTool(message.params));
|
|
@@ -361,7 +403,16 @@ export class McpBrowserDevToolsServer {
|
|
|
361
403
|
try {
|
|
362
404
|
const tool = this.tools.get(params.name);
|
|
363
405
|
if (!tool) {
|
|
364
|
-
|
|
406
|
+
const group = Object.entries(TOOL_GROUPS).find(([, names]) =>
|
|
407
|
+
names.includes(params.name),
|
|
408
|
+
)?.[0];
|
|
409
|
+
throw new Error(
|
|
410
|
+
params.name === "evaluate_js" && !this.config.enableEvaluate
|
|
411
|
+
? "evaluate_js is turned off by MCP_BROWSER_ENABLE_EVAL=0"
|
|
412
|
+
: group
|
|
413
|
+
? `${params.name} is not listed directly; call it through more_tools ({"name":"${params.name}","arguments":{...}}) or as a run_steps step, or list it with MCP_BROWSER_TOOLS=${group}`
|
|
414
|
+
: `Unknown tool: ${params.name}`,
|
|
415
|
+
);
|
|
365
416
|
}
|
|
366
417
|
|
|
367
418
|
const args = params.arguments ?? {};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// set_network: block or mock requests by URL glob, add request headers,
|
|
2
|
+
// and emulate offline or slow networks. The state lives on the session; a
|
|
3
|
+
// call replaces the fields it gives and keeps the rest.
|
|
4
|
+
|
|
5
|
+
// The glob syntax of CDP's Fetch patterns, so a rule matches the same URLs
|
|
6
|
+
// on both browsers: * is any run of characters, ? exactly one, and a
|
|
7
|
+
// backslash escapes the next character.
|
|
8
|
+
export function globToRegExp(glob) {
|
|
9
|
+
let source = "";
|
|
10
|
+
for (let index = 0; index < glob.length; index += 1) {
|
|
11
|
+
const char = glob[index];
|
|
12
|
+
if (char === "\\" && index + 1 < glob.length) {
|
|
13
|
+
index += 1;
|
|
14
|
+
source += glob[index].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
15
|
+
} else if (char === "*") {
|
|
16
|
+
source += ".*";
|
|
17
|
+
} else if (char === "?") {
|
|
18
|
+
source += ".";
|
|
19
|
+
} else {
|
|
20
|
+
source += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return new RegExp(`^${source}$`, "s");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Runs fn after the session's earlier network calls, so overlapping calls
|
|
27
|
+
// (and a detach) apply one at a time in the order they came.
|
|
28
|
+
export async function inNetworkTurn(session, fn) {
|
|
29
|
+
const previous = session.networkTurn ?? Promise.resolve();
|
|
30
|
+
let finished;
|
|
31
|
+
session.networkTurn = new Promise((resolve) => {
|
|
32
|
+
finished = resolve;
|
|
33
|
+
});
|
|
34
|
+
await previous.catch(() => {});
|
|
35
|
+
try {
|
|
36
|
+
return await fn();
|
|
37
|
+
} finally {
|
|
38
|
+
finished();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function emptyNetworkState() {
|
|
43
|
+
return {
|
|
44
|
+
rules: [],
|
|
45
|
+
headers: {},
|
|
46
|
+
offline: false,
|
|
47
|
+
latencyMs: 0,
|
|
48
|
+
downloadKbps: null,
|
|
49
|
+
uploadKbps: null,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
54
|
+
|
|
55
|
+
// Browsers reject a request or response with a malformed header, which
|
|
56
|
+
// would leave a paused request unanswered, so headers are checked first.
|
|
57
|
+
function checkHeaders(headers, where) {
|
|
58
|
+
for (const [name, value] of Object.entries(headers ?? {})) {
|
|
59
|
+
if (!HEADER_NAME.test(name)) {
|
|
60
|
+
throw new Error(`${where} has an invalid header name: ${name}`);
|
|
61
|
+
}
|
|
62
|
+
if (/[\r\n\0]/.test(String(value))) {
|
|
63
|
+
throw new Error(`${where} header ${name} has a line break in its value`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// The state after a set_network call: reset starts from nothing, and each
|
|
69
|
+
// field given replaces the one before. Rule hit counts start at zero.
|
|
70
|
+
export function applyNetworkOptions(current, options) {
|
|
71
|
+
checkHeaders(options.headers, "headers");
|
|
72
|
+
for (const [index, rule] of (options.rules ?? []).entries()) {
|
|
73
|
+
checkHeaders(rule.headers, `rules[${index}]`);
|
|
74
|
+
if (rule.contentType !== undefined) {
|
|
75
|
+
checkHeaders({ "content-type": rule.contentType }, `rules[${index}]`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const state = options.reset
|
|
79
|
+
? emptyNetworkState()
|
|
80
|
+
: { ...(current ?? emptyNetworkState()) };
|
|
81
|
+
if (options.rules !== undefined) {
|
|
82
|
+
state.rules = options.rules.map((rule) => ({
|
|
83
|
+
url: rule.url,
|
|
84
|
+
action: rule.action,
|
|
85
|
+
status: rule.status ?? 200,
|
|
86
|
+
contentType: rule.contentType ?? null,
|
|
87
|
+
body: rule.body ?? "",
|
|
88
|
+
headers: rule.headers ?? {},
|
|
89
|
+
pattern: globToRegExp(rule.url),
|
|
90
|
+
hits: 0,
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
93
|
+
for (const key of [
|
|
94
|
+
"headers",
|
|
95
|
+
"offline",
|
|
96
|
+
"latencyMs",
|
|
97
|
+
"downloadKbps",
|
|
98
|
+
"uploadKbps",
|
|
99
|
+
]) {
|
|
100
|
+
if (options[key] !== undefined) {
|
|
101
|
+
state[key] = options[key];
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return state;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function throttled(state) {
|
|
108
|
+
return Boolean(state.latencyMs || state.downloadKbps || state.uploadKbps);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// The first rule whose pattern matches url, with its hit counted.
|
|
112
|
+
export function takeMatchingRule(state, url) {
|
|
113
|
+
const rule = state?.rules.find((candidate) => candidate.pattern.test(url));
|
|
114
|
+
if (rule) {
|
|
115
|
+
rule.hits += 1;
|
|
116
|
+
}
|
|
117
|
+
return rule ?? null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// A mock's response headers as name/value pairs. Mocks usually stand in
|
|
121
|
+
// for an API the page fetches across origins, so CORS is allowed unless
|
|
122
|
+
// the rule says otherwise.
|
|
123
|
+
export function mockHeaders(rule) {
|
|
124
|
+
const headers = { ...rule.headers };
|
|
125
|
+
const names = new Set(Object.keys(headers).map((name) => name.toLowerCase()));
|
|
126
|
+
if (rule.contentType && !names.has("content-type")) {
|
|
127
|
+
headers["content-type"] = rule.contentType;
|
|
128
|
+
}
|
|
129
|
+
if (!names.has("access-control-allow-origin")) {
|
|
130
|
+
headers["access-control-allow-origin"] = "*";
|
|
131
|
+
}
|
|
132
|
+
return Object.entries(headers).map(([name, value]) => ({
|
|
133
|
+
name,
|
|
134
|
+
value: String(value),
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function describeNetworkState(state) {
|
|
139
|
+
return {
|
|
140
|
+
rules: state.rules.map(({ url, action, status, hits }) => ({
|
|
141
|
+
url,
|
|
142
|
+
action,
|
|
143
|
+
...(action === "mock" ? { status } : {}),
|
|
144
|
+
hits,
|
|
145
|
+
})),
|
|
146
|
+
headers: Object.keys(state.headers),
|
|
147
|
+
offline: state.offline,
|
|
148
|
+
...(throttled(state)
|
|
149
|
+
? {
|
|
150
|
+
latencyMs: state.latencyMs,
|
|
151
|
+
downloadKbps: state.downloadKbps,
|
|
152
|
+
uploadKbps: state.uploadKbps,
|
|
153
|
+
}
|
|
154
|
+
: {}),
|
|
155
|
+
};
|
|
156
|
+
}
|
package/src/page-context.mjs
CHANGED
|
@@ -11,13 +11,32 @@ export function buildInputRecorderExpression(early) {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
// Builds an expression that runs pageScript in the page with this payload.
|
|
14
|
-
// With serialize, the expression evaluates to the result as a JSON string
|
|
14
|
+
// With serialize, the expression evaluates to the result as a JSON string,
|
|
15
|
+
// or, for an action that returns a promise, to a promise of one.
|
|
15
16
|
export function buildPageContextExpression(
|
|
16
17
|
payload,
|
|
17
18
|
{ serialize = false } = {},
|
|
18
19
|
) {
|
|
19
20
|
const body = `(${PAGE_SCRIPT_SOURCE})(${JSON.stringify(payload)})`;
|
|
20
|
-
return serialize
|
|
21
|
+
return serialize
|
|
22
|
+
? `((result) => result && typeof result.then === "function" ? result.then(JSON.stringify) : JSON.stringify(result))(${body})`
|
|
23
|
+
: body;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Refs (e12) are numbered per page from refStart. The server remembers the
|
|
27
|
+
// page's next ref on the session and passes it on, so numbering continues
|
|
28
|
+
// across navigations and a ref from an earlier page never resolves on a
|
|
29
|
+
// later one. The page reports nextRef with each snapshot; it is bookkeeping,
|
|
30
|
+
// so it is removed from the result.
|
|
31
|
+
export function takeNextRef(session, result) {
|
|
32
|
+
if (result && typeof result === "object" && "nextRef" in result) {
|
|
33
|
+
const { nextRef, ...rest } = result;
|
|
34
|
+
if (Number.isInteger(nextRef) && nextRef > (session.refStart ?? 1)) {
|
|
35
|
+
session.refStart = nextRef;
|
|
36
|
+
}
|
|
37
|
+
return rest;
|
|
38
|
+
}
|
|
39
|
+
return result;
|
|
21
40
|
}
|
|
22
41
|
|
|
23
42
|
function describeTarget(target) {
|
|
@@ -70,3 +89,288 @@ export function assertEnabled(target) {
|
|
|
70
89
|
throw notActionable(`Element "${target.selector}" is disabled`);
|
|
71
90
|
}
|
|
72
91
|
}
|
|
92
|
+
|
|
93
|
+
// A pointer target is a locator, which resolves to the center of its
|
|
94
|
+
// element's visible area, or viewport coordinates { x, y } in CSS pixels.
|
|
95
|
+
export function describePointer(target) {
|
|
96
|
+
return typeof target === "string"
|
|
97
|
+
? `"${target}"`
|
|
98
|
+
: `(${target.x}, ${target.y})`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// The fields an action reports about where it acted: the selector and its
|
|
102
|
+
// element, or the element found at the coordinates.
|
|
103
|
+
export function pointerFields(target, resolved, node = resolved.node) {
|
|
104
|
+
return typeof target === "string"
|
|
105
|
+
? { selector: target, point: resolved.point, node }
|
|
106
|
+
: { point: resolved.point, target: resolved.target };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// A drag reports where it pressed and released, without element details.
|
|
110
|
+
export function dragEnd(target, resolved) {
|
|
111
|
+
return typeof target === "string"
|
|
112
|
+
? { selector: target, point: resolved.point }
|
|
113
|
+
: { point: resolved.point, target: resolved.target };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export const DEFAULT_DRAG_STEPS = 10;
|
|
117
|
+
|
|
118
|
+
// The points a drag moves through after pressing at from, ending at to, so
|
|
119
|
+
// pages that track the pointer see a path rather than a jump.
|
|
120
|
+
export function dragPath(from, to, steps = DEFAULT_DRAG_STEPS) {
|
|
121
|
+
return Array.from({ length: steps }, (_, index) => {
|
|
122
|
+
const fraction = (index + 1) / steps;
|
|
123
|
+
return {
|
|
124
|
+
x: from.x + (to.x - from.x) * fraction,
|
|
125
|
+
y: from.y + (to.y - from.y) * fraction,
|
|
126
|
+
};
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export const MOUSE_BUTTONS = ["left", "middle", "right"];
|
|
131
|
+
|
|
132
|
+
// Whether scroll sends a mouse wheel rather than scrolling from the page.
|
|
133
|
+
export function wheelScroll(options) {
|
|
134
|
+
const deltas = options.deltaX !== undefined || options.deltaY !== undefined;
|
|
135
|
+
return options.x !== undefined || Boolean(options.selector && deltas);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// An expression that takes the file input fileInput() left on the window
|
|
139
|
+
// under token, removing it there.
|
|
140
|
+
export function takeFileTarget(token) {
|
|
141
|
+
const key = JSON.stringify(token);
|
|
142
|
+
return `(() => { const targets = window.__mcpBrowserDevToolsFileTargets; const input = targets?.get(${key}); targets?.delete(${key}); return input; })()`;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Checks a file input before files are set on it.
|
|
146
|
+
export function assertFileInput(target, files) {
|
|
147
|
+
if (target.disabled) {
|
|
148
|
+
throw notActionable(`File input "${target.selector}" is disabled`);
|
|
149
|
+
}
|
|
150
|
+
if (files.length > 1 && !target.multiple) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
`File input "${target.selector}" takes one file, not ${files.length}`,
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function uploadResult(browserFamily, selector, files, extra = {}) {
|
|
158
|
+
return {
|
|
159
|
+
browserFamily,
|
|
160
|
+
selector,
|
|
161
|
+
found: true,
|
|
162
|
+
uploaded: files.map((file) => file.split(/[\\/]/).pop()),
|
|
163
|
+
...extra,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Frames: get_snapshot lists the controls inside iframes with refs like
|
|
168
|
+
// f2e7, element e7 of frame f2. The server keeps the frame keys; a tool
|
|
169
|
+
// given such a ref runs its page action in that frame, with the ref
|
|
170
|
+
// rewritten to the frame's own e7, and shifts the points it reports by the
|
|
171
|
+
// frame's position, so input lands where the element is.
|
|
172
|
+
export const MAX_SNAPSHOT_FRAMES = 10;
|
|
173
|
+
|
|
174
|
+
export function parseFrameRef(selector) {
|
|
175
|
+
const match =
|
|
176
|
+
typeof selector === "string"
|
|
177
|
+
? selector.trim().match(/^ref=f(\d+)(e\d+)$/)
|
|
178
|
+
: null;
|
|
179
|
+
return match
|
|
180
|
+
? { frameKey: `f${match[1]}`, selector: `ref=${match[2]}` }
|
|
181
|
+
: null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Frame keys for one session, stable for a frame while it exists. Each
|
|
185
|
+
// frame carries its own next ref, as the session does for the top page.
|
|
186
|
+
export class FrameKeys {
|
|
187
|
+
constructor() {
|
|
188
|
+
this.byKey = new Map();
|
|
189
|
+
this.byId = new Map();
|
|
190
|
+
this.next = 1;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
keyFor(id, frame) {
|
|
194
|
+
let key = this.byId.get(id);
|
|
195
|
+
if (!key) {
|
|
196
|
+
key = `f${this.next++}`;
|
|
197
|
+
this.byId.set(id, key);
|
|
198
|
+
}
|
|
199
|
+
this.byKey.set(key, { ...(this.byKey.get(key) ?? {}), ...frame, id, key });
|
|
200
|
+
return key;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
get(key) {
|
|
204
|
+
return this.byKey.get(key) ?? null;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function unknownFrame(frameKey, selector) {
|
|
209
|
+
return {
|
|
210
|
+
found: false,
|
|
211
|
+
selector,
|
|
212
|
+
error: `Unknown frame ${frameKey}: frame refs come from get_snapshot, and the frame may have gone; call get_snapshot again`,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// A result from a frame names the selector the tool was given, with its
|
|
217
|
+
// frame, rather than the frame's own ref.
|
|
218
|
+
export function restoreFrameSelector(result, route, selector) {
|
|
219
|
+
return result &&
|
|
220
|
+
typeof result === "object" &&
|
|
221
|
+
result.selector === route.selector
|
|
222
|
+
? { ...result, selector }
|
|
223
|
+
: result;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// A change report from a frame, with its refs carrying the frame's key.
|
|
227
|
+
export function prefixFrameReport(report, frameKey) {
|
|
228
|
+
if (!report || typeof report !== "object") {
|
|
229
|
+
return report;
|
|
230
|
+
}
|
|
231
|
+
const prefix = (line) => line.replace(/^e(\d+)/, `${frameKey}e$1`);
|
|
232
|
+
const lists = Object.fromEntries(
|
|
233
|
+
["added", "removed", "updated"]
|
|
234
|
+
.filter((key) => report[key]?.lines)
|
|
235
|
+
.map((key) => [
|
|
236
|
+
key,
|
|
237
|
+
{ ...report[key], lines: report[key].lines.map(prefix) },
|
|
238
|
+
]),
|
|
239
|
+
);
|
|
240
|
+
return {
|
|
241
|
+
...report,
|
|
242
|
+
...lists,
|
|
243
|
+
...(Array.isArray(report.nodes) ? { nodes: report.nodes.map(prefix) } : {}),
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Moves the points a page action in a frame reports into the top page's
|
|
248
|
+
// viewport.
|
|
249
|
+
export function shiftFramePoints(result, offset) {
|
|
250
|
+
if (!result || typeof result !== "object" || !offset) {
|
|
251
|
+
return result;
|
|
252
|
+
}
|
|
253
|
+
const shifted = { ...result };
|
|
254
|
+
if (result.point) {
|
|
255
|
+
shifted.point = {
|
|
256
|
+
x: result.point.x + offset.x,
|
|
257
|
+
y: result.point.y + offset.y,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
if (result.node?.box) {
|
|
261
|
+
const box = result.node.box;
|
|
262
|
+
shifted.node = {
|
|
263
|
+
...result.node,
|
|
264
|
+
box: {
|
|
265
|
+
...box,
|
|
266
|
+
x: box.x + offset.x,
|
|
267
|
+
y: box.y + offset.y,
|
|
268
|
+
left: box.left + offset.x,
|
|
269
|
+
right: box.right + offset.x,
|
|
270
|
+
top: box.top + offset.y,
|
|
271
|
+
bottom: box.bottom + offset.y,
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
return shifted;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// A frame's snapshot lines, after a header naming the frame, with refs
|
|
279
|
+
// carrying the frame's key.
|
|
280
|
+
export function frameSnapshotLines(frameKey, frame, result) {
|
|
281
|
+
const header =
|
|
282
|
+
`${frameKey} frame ${JSON.stringify(result.title ?? "")} ${result.url ?? frame.url ?? ""}`.trim();
|
|
283
|
+
const lines = (result.nodes ?? []).map((line) =>
|
|
284
|
+
line.replace(/^e(\d+)/, `${frameKey}e$1`),
|
|
285
|
+
);
|
|
286
|
+
if (result.more > 0) {
|
|
287
|
+
lines.push(`(${result.more} more nodes in ${frameKey})`);
|
|
288
|
+
}
|
|
289
|
+
return [header, ...lines];
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Adds the frames' snapshots to the top page's: each frame with nodes gets
|
|
293
|
+
// a header and its lines. A frame's refs number on from its own last
|
|
294
|
+
// snapshot, as the top page's do. Frames without a box are left out.
|
|
295
|
+
export async function addFrameSnapshots({
|
|
296
|
+
result,
|
|
297
|
+
frames,
|
|
298
|
+
frameKeys,
|
|
299
|
+
runInFrame,
|
|
300
|
+
options,
|
|
301
|
+
}) {
|
|
302
|
+
if (!result?.found || !Array.isArray(result.nodes)) {
|
|
303
|
+
return result;
|
|
304
|
+
}
|
|
305
|
+
const nodes = [...result.nodes];
|
|
306
|
+
let shown = 0;
|
|
307
|
+
for (const frame of frames) {
|
|
308
|
+
if (shown >= MAX_SNAPSHOT_FRAMES) {
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
const key = frameKeys.keyFor(frame.id, frame);
|
|
312
|
+
const entry = frameKeys.get(key);
|
|
313
|
+
let snapshot;
|
|
314
|
+
try {
|
|
315
|
+
snapshot = await runInFrame(
|
|
316
|
+
key,
|
|
317
|
+
{
|
|
318
|
+
action: "snapshot",
|
|
319
|
+
limit: options.limit,
|
|
320
|
+
headings: options.headings,
|
|
321
|
+
refStart: entry.refStart ?? 1,
|
|
322
|
+
},
|
|
323
|
+
{ scroll: false },
|
|
324
|
+
);
|
|
325
|
+
} catch {
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (!snapshot?.found) {
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
snapshot = takeNextRef(entry, snapshot);
|
|
332
|
+
if (snapshot.nodes.length === 0) {
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
nodes.push(...frameSnapshotLines(key, frame, snapshot));
|
|
336
|
+
shown += 1;
|
|
337
|
+
}
|
|
338
|
+
return { ...result, nodes };
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// A snapshot of one element inside a frame, named by a frame ref.
|
|
342
|
+
export async function frameElementSnapshot({
|
|
343
|
+
route,
|
|
344
|
+
frameKeys,
|
|
345
|
+
runInFrame,
|
|
346
|
+
options,
|
|
347
|
+
}) {
|
|
348
|
+
const entry = frameKeys.get(route.frameKey);
|
|
349
|
+
if (!entry) {
|
|
350
|
+
return unknownFrame(route.frameKey, options.selector);
|
|
351
|
+
}
|
|
352
|
+
const snapshot = await runInFrame(route.frameKey, {
|
|
353
|
+
action: "snapshot",
|
|
354
|
+
selector: route.selector,
|
|
355
|
+
limit: options.limit,
|
|
356
|
+
headings: options.headings,
|
|
357
|
+
refStart: entry.refStart ?? 1,
|
|
358
|
+
});
|
|
359
|
+
if (!snapshot?.found) {
|
|
360
|
+
return snapshot;
|
|
361
|
+
}
|
|
362
|
+
const { nodes, more, ...rest } = takeNextRef(entry, snapshot);
|
|
363
|
+
return {
|
|
364
|
+
...rest,
|
|
365
|
+
nodes: nodes.map((line) => line.replace(/^e(\d+)/, `${route.frameKey}e$1`)),
|
|
366
|
+
more,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// The scope a delivery probe was armed in: the frame of a frame ref, else
|
|
371
|
+
// the top document. Passed as the probe's selector, so it is read there.
|
|
372
|
+
export function probeScope(target) {
|
|
373
|
+
return typeof target === "string" && parseFrameRef(target)
|
|
374
|
+
? { selector: target }
|
|
375
|
+
: {};
|
|
376
|
+
}
|