@wordbricks/playwright-mcp 0.1.24 → 0.1.26
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/lib/browserContextFactory.js +399 -0
- package/lib/browserServerBackend.js +86 -0
- package/lib/config.js +300 -0
- package/lib/context.js +311 -0
- package/lib/extension/cdpRelay.js +352 -0
- package/lib/extension/extensionContextFactory.js +56 -0
- package/lib/frameworkPatterns.js +35 -0
- package/lib/hooks/antiBotDetectionHook.js +178 -0
- package/lib/hooks/core.js +145 -0
- package/lib/hooks/eventConsumer.js +52 -0
- package/lib/hooks/events.js +42 -0
- package/lib/hooks/formatToolCallEvent.js +12 -0
- package/lib/hooks/frameworkStateHook.js +182 -0
- package/lib/hooks/grouping.js +72 -0
- package/lib/hooks/jsonLdDetectionHook.js +182 -0
- package/lib/hooks/networkFilters.js +82 -0
- package/lib/hooks/networkSetup.js +61 -0
- package/lib/hooks/networkTrackingHook.js +67 -0
- package/lib/hooks/pageHeightHook.js +75 -0
- package/lib/hooks/registry.js +41 -0
- package/lib/hooks/requireTabHook.js +26 -0
- package/lib/hooks/schema.js +89 -0
- package/lib/hooks/waitHook.js +33 -0
- package/lib/index.js +41 -0
- package/lib/mcp/inProcessTransport.js +71 -0
- package/lib/mcp/proxyBackend.js +130 -0
- package/lib/mcp/server.js +91 -0
- package/lib/mcp/tool.js +44 -0
- package/lib/mcp/transport.js +188 -0
- package/lib/playwrightTransformer.js +520 -0
- package/lib/program.js +112 -0
- package/lib/response.js +192 -0
- package/lib/sessionLog.js +123 -0
- package/lib/tab.js +251 -0
- package/lib/tools/common.js +55 -0
- package/lib/tools/console.js +33 -0
- package/lib/tools/dialogs.js +50 -0
- package/lib/tools/evaluate.js +62 -0
- package/lib/tools/extractFrameworkState.js +225 -0
- package/lib/tools/files.js +48 -0
- package/lib/tools/form.js +66 -0
- package/lib/tools/getSnapshot.js +36 -0
- package/lib/tools/getVisibleHtml.js +68 -0
- package/lib/tools/install.js +51 -0
- package/lib/tools/keyboard.js +83 -0
- package/lib/tools/mouse.js +97 -0
- package/lib/tools/navigate.js +66 -0
- package/lib/tools/network.js +121 -0
- package/lib/tools/networkDetail.js +238 -0
- package/lib/tools/networkSearch/bodySearch.js +161 -0
- package/lib/tools/networkSearch/grouping.js +37 -0
- package/lib/tools/networkSearch/helpers.js +32 -0
- package/lib/tools/networkSearch/searchHtml.js +76 -0
- package/lib/tools/networkSearch/types.js +1 -0
- package/lib/tools/networkSearch/urlSearch.js +124 -0
- package/lib/tools/networkSearch.js +278 -0
- package/lib/tools/pdf.js +41 -0
- package/lib/tools/repl.js +414 -0
- package/lib/tools/screenshot.js +103 -0
- package/lib/tools/scroll.js +131 -0
- package/lib/tools/snapshot.js +161 -0
- package/lib/tools/tabs.js +62 -0
- package/lib/tools/tool.js +35 -0
- package/lib/tools/utils.js +78 -0
- package/lib/tools/wait.js +60 -0
- package/lib/tools.js +68 -0
- package/lib/utils/adBlockFilter.js +90 -0
- package/lib/utils/codegen.js +55 -0
- package/lib/utils/extensionPath.js +10 -0
- package/lib/utils/fileUtils.js +40 -0
- package/lib/utils/graphql.js +269 -0
- package/lib/utils/guid.js +22 -0
- package/lib/utils/httpServer.js +39 -0
- package/lib/utils/log.js +21 -0
- package/lib/utils/manualPromise.js +111 -0
- package/lib/utils/networkFormat.js +14 -0
- package/lib/utils/package.js +20 -0
- package/lib/utils/result.js +2 -0
- package/lib/utils/sanitizeHtml.js +130 -0
- package/lib/utils/truncate.js +103 -0
- package/lib/utils/withTimeout.js +7 -0
- package/package.json +11 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Microsoft Corporation.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
import * as javascript from "../utils/codegen.js";
|
|
18
|
+
import { elementSchema } from "./snapshot.js";
|
|
19
|
+
import { defineTabTool } from "./tool.js";
|
|
20
|
+
import { generateLocator } from "./utils.js";
|
|
21
|
+
const pressKey = defineTabTool({
|
|
22
|
+
capability: "core",
|
|
23
|
+
schema: {
|
|
24
|
+
name: "browser_press_key",
|
|
25
|
+
title: "Press a key",
|
|
26
|
+
description: "Press a key on the keyboard",
|
|
27
|
+
inputSchema: z.object({
|
|
28
|
+
key: z
|
|
29
|
+
.string()
|
|
30
|
+
.describe("Name of the key to press or a character to generate, such as `ArrowLeft` or `a`"),
|
|
31
|
+
}),
|
|
32
|
+
type: "input",
|
|
33
|
+
},
|
|
34
|
+
handle: async (tab, params, response) => {
|
|
35
|
+
response.setIncludeSnapshot();
|
|
36
|
+
response.addCode(`// Press ${params.key}`);
|
|
37
|
+
response.addCode(`await page.keyboard.press('${params.key}');`);
|
|
38
|
+
await tab.waitForCompletion(async () => {
|
|
39
|
+
await tab.page.keyboard.press(params.key);
|
|
40
|
+
});
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
const typeSchema = elementSchema.extend({
|
|
44
|
+
text: z.string().describe("Text to type into the element"),
|
|
45
|
+
submit: z
|
|
46
|
+
.boolean()
|
|
47
|
+
.optional()
|
|
48
|
+
.describe("Whether to submit entered text (press Enter after)"),
|
|
49
|
+
slowly: z
|
|
50
|
+
.boolean()
|
|
51
|
+
.optional()
|
|
52
|
+
.describe("Whether to type one character at a time. Useful for triggering key handlers in the page. By default entire text is filled in at once."),
|
|
53
|
+
});
|
|
54
|
+
const type = defineTabTool({
|
|
55
|
+
capability: "core",
|
|
56
|
+
schema: {
|
|
57
|
+
name: "browser_type",
|
|
58
|
+
title: "Type text",
|
|
59
|
+
description: "Type text into editable element",
|
|
60
|
+
inputSchema: typeSchema,
|
|
61
|
+
type: "input",
|
|
62
|
+
},
|
|
63
|
+
handle: async (tab, params, response) => {
|
|
64
|
+
const locator = await tab.refLocator(params);
|
|
65
|
+
await tab.waitForCompletion(async () => {
|
|
66
|
+
if (params.slowly) {
|
|
67
|
+
response.setIncludeSnapshot();
|
|
68
|
+
response.addCode(`await page.${await generateLocator(locator)}.pressSequentially(${javascript.quote(params.text)});`);
|
|
69
|
+
await locator.pressSequentially(params.text);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
response.addCode(`await page.${await generateLocator(locator)}.fill(${javascript.quote(params.text)});`);
|
|
73
|
+
await locator.fill(params.text);
|
|
74
|
+
}
|
|
75
|
+
if (params.submit) {
|
|
76
|
+
response.setIncludeSnapshot();
|
|
77
|
+
response.addCode(`await page.${await generateLocator(locator)}.press('Enter');`);
|
|
78
|
+
await locator.press("Enter");
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
export default [pressKey, type];
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Microsoft Corporation.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
import { defineTabTool } from "./tool.js";
|
|
18
|
+
const elementSchema = z.object({
|
|
19
|
+
element: z
|
|
20
|
+
.string()
|
|
21
|
+
.describe("Human-readable element description used to obtain permission to interact with the element"),
|
|
22
|
+
});
|
|
23
|
+
const mouseMove = defineTabTool({
|
|
24
|
+
capability: "vision",
|
|
25
|
+
schema: {
|
|
26
|
+
name: "browser_mouse_move_xy",
|
|
27
|
+
title: "Move mouse",
|
|
28
|
+
description: "Move mouse to a given position",
|
|
29
|
+
inputSchema: elementSchema.extend({
|
|
30
|
+
x: z.number().describe("X coordinate"),
|
|
31
|
+
y: z.number().describe("Y coordinate"),
|
|
32
|
+
}),
|
|
33
|
+
type: "readOnly",
|
|
34
|
+
},
|
|
35
|
+
handle: async (tab, params, response) => {
|
|
36
|
+
response.addCode(`// Move mouse to (${params.x}, ${params.y})`);
|
|
37
|
+
response.addCode(`await page.mouse.move(${params.x}, ${params.y});`);
|
|
38
|
+
await tab.waitForCompletion(async () => {
|
|
39
|
+
await tab.page.mouse.move(params.x, params.y);
|
|
40
|
+
});
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
const mouseClick = defineTabTool({
|
|
44
|
+
capability: "vision",
|
|
45
|
+
schema: {
|
|
46
|
+
name: "browser_mouse_click_xy",
|
|
47
|
+
title: "Click",
|
|
48
|
+
description: "Click left mouse button at a given position",
|
|
49
|
+
inputSchema: elementSchema.extend({
|
|
50
|
+
x: z.number().describe("X coordinate"),
|
|
51
|
+
y: z.number().describe("Y coordinate"),
|
|
52
|
+
}),
|
|
53
|
+
type: "input",
|
|
54
|
+
},
|
|
55
|
+
handle: async (tab, params, response) => {
|
|
56
|
+
response.setIncludeSnapshot();
|
|
57
|
+
response.addCode(`// Click mouse at coordinates (${params.x}, ${params.y})`);
|
|
58
|
+
response.addCode(`await page.mouse.move(${params.x}, ${params.y});`);
|
|
59
|
+
response.addCode(`await page.mouse.down();`);
|
|
60
|
+
response.addCode(`await page.mouse.up();`);
|
|
61
|
+
await tab.waitForCompletion(async () => {
|
|
62
|
+
await tab.page.mouse.move(params.x, params.y);
|
|
63
|
+
await tab.page.mouse.down();
|
|
64
|
+
await tab.page.mouse.up();
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
const mouseDrag = defineTabTool({
|
|
69
|
+
capability: "vision",
|
|
70
|
+
schema: {
|
|
71
|
+
name: "browser_mouse_drag_xy",
|
|
72
|
+
title: "Drag mouse",
|
|
73
|
+
description: "Drag left mouse button to a given position",
|
|
74
|
+
inputSchema: elementSchema.extend({
|
|
75
|
+
startX: z.number().describe("Start X coordinate"),
|
|
76
|
+
startY: z.number().describe("Start Y coordinate"),
|
|
77
|
+
endX: z.number().describe("End X coordinate"),
|
|
78
|
+
endY: z.number().describe("End Y coordinate"),
|
|
79
|
+
}),
|
|
80
|
+
type: "input",
|
|
81
|
+
},
|
|
82
|
+
handle: async (tab, params, response) => {
|
|
83
|
+
response.setIncludeSnapshot();
|
|
84
|
+
response.addCode(`// Drag mouse from (${params.startX}, ${params.startY}) to (${params.endX}, ${params.endY})`);
|
|
85
|
+
response.addCode(`await page.mouse.move(${params.startX}, ${params.startY});`);
|
|
86
|
+
response.addCode(`await page.mouse.down();`);
|
|
87
|
+
response.addCode(`await page.mouse.move(${params.endX}, ${params.endY});`);
|
|
88
|
+
response.addCode(`await page.mouse.up();`);
|
|
89
|
+
await tab.waitForCompletion(async () => {
|
|
90
|
+
await tab.page.mouse.move(params.startX, params.startY);
|
|
91
|
+
await tab.page.mouse.down();
|
|
92
|
+
await tab.page.mouse.move(params.endX, params.endY);
|
|
93
|
+
await tab.page.mouse.up();
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
export default [mouseMove, mouseClick, mouseDrag];
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Microsoft Corporation.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
import { defineTabTool, defineTool } from "./tool.js";
|
|
18
|
+
const navigate = defineTool({
|
|
19
|
+
capability: "core",
|
|
20
|
+
schema: {
|
|
21
|
+
name: "browser_navigate",
|
|
22
|
+
title: "Navigate to a URL",
|
|
23
|
+
description: "Navigate to a URL",
|
|
24
|
+
inputSchema: z.object({
|
|
25
|
+
url: z.string().describe("The URL to navigate to"),
|
|
26
|
+
}),
|
|
27
|
+
type: "action",
|
|
28
|
+
},
|
|
29
|
+
handle: async (context, params, response) => {
|
|
30
|
+
const tab = await context.ensureTab();
|
|
31
|
+
await tab.navigate(params.url);
|
|
32
|
+
response.setIncludeSnapshot();
|
|
33
|
+
response.addCode(`await page.goto('${params.url}');`);
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
const goBack = defineTabTool({
|
|
37
|
+
capability: "core",
|
|
38
|
+
schema: {
|
|
39
|
+
name: "browser_navigate_back",
|
|
40
|
+
title: "Go back",
|
|
41
|
+
description: "Go back to the previous page",
|
|
42
|
+
inputSchema: z.object({}),
|
|
43
|
+
type: "readOnly",
|
|
44
|
+
},
|
|
45
|
+
handle: async (tab, params, response) => {
|
|
46
|
+
await tab.page.goBack();
|
|
47
|
+
response.setIncludeSnapshot();
|
|
48
|
+
response.addCode(`await page.goBack();`);
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
const goForward = defineTabTool({
|
|
52
|
+
capability: "core",
|
|
53
|
+
schema: {
|
|
54
|
+
name: "browser_navigate_forward",
|
|
55
|
+
title: "Go forward",
|
|
56
|
+
description: "Go forward to the next page",
|
|
57
|
+
inputSchema: z.object({}),
|
|
58
|
+
type: "readOnly",
|
|
59
|
+
},
|
|
60
|
+
handle: async (tab, params, response) => {
|
|
61
|
+
await tab.page.goForward();
|
|
62
|
+
response.setIncludeSnapshot();
|
|
63
|
+
response.addCode(`await page.goForward();`);
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
export default [navigate, goBack, goForward];
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Microsoft Corporation.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
import { formatUrlWithTrimmedParams } from "../hooks/networkFilters.js";
|
|
18
|
+
import { defineTabTool } from "./tool.js";
|
|
19
|
+
// const requests = defineTool({
|
|
20
|
+
// capability: 'core',
|
|
21
|
+
// schema: {
|
|
22
|
+
// name: 'browser_network_requests',
|
|
23
|
+
// title: 'List network requests',
|
|
24
|
+
// description: 'Returns all network requests since loading the page',
|
|
25
|
+
// inputSchema: z.object({}),
|
|
26
|
+
// type: 'readOnly',
|
|
27
|
+
// },
|
|
28
|
+
// handle: async ctx => {
|
|
29
|
+
// const reqs = await pipe(
|
|
30
|
+
// ctx.currentTabOrDie().requests().entries(),
|
|
31
|
+
// filter(([request, response]) => ['document', 'xhr', 'fetch'].includes(request.resourceType())),
|
|
32
|
+
// // GET, POST
|
|
33
|
+
// filter(([request, response]) => ['GET', 'POST'].includes(request.method())),
|
|
34
|
+
// // 2xx
|
|
35
|
+
// filter(([request, response]) => response?.ok()),
|
|
36
|
+
// // 204 No Content
|
|
37
|
+
// reject(([request, response]) => response?.status() === 204),
|
|
38
|
+
// // body length > 0
|
|
39
|
+
// toAsync,
|
|
40
|
+
// filter(([request, response]) => response ? withTimeout(response.body(), 500).catch(() => []).then(body => body.length > 0) : Promise.resolve(false)),
|
|
41
|
+
// uniqBy(([request, response]) => JSON.stringify({
|
|
42
|
+
// url: request.url(),
|
|
43
|
+
// body: request.postData(),
|
|
44
|
+
// })),
|
|
45
|
+
// toArray,
|
|
46
|
+
// );
|
|
47
|
+
// const lines = await Promise.all(
|
|
48
|
+
// reqs.map(([request, response]) => renderRequest(request, response))
|
|
49
|
+
// );
|
|
50
|
+
// const log = lines.join('\n');
|
|
51
|
+
// return {
|
|
52
|
+
// code: [`// <internal code to list network requests>`],
|
|
53
|
+
// action: async () => {
|
|
54
|
+
// return {
|
|
55
|
+
// content: [{ type: 'text', text: log }]
|
|
56
|
+
// };
|
|
57
|
+
// },
|
|
58
|
+
// captureSnapshot: false,
|
|
59
|
+
// waitForNetwork: false,
|
|
60
|
+
// };
|
|
61
|
+
// },
|
|
62
|
+
// });
|
|
63
|
+
const requests = defineTabTool({
|
|
64
|
+
capability: "core",
|
|
65
|
+
schema: {
|
|
66
|
+
name: "browser_network_requests",
|
|
67
|
+
title: "List network requests",
|
|
68
|
+
description: "Returns all network requests since loading the page",
|
|
69
|
+
inputSchema: z.object({}),
|
|
70
|
+
type: "readOnly",
|
|
71
|
+
},
|
|
72
|
+
handle: async (tab, params, response) => {
|
|
73
|
+
const requests = tab.requests();
|
|
74
|
+
for (const [req, res] of requests.entries())
|
|
75
|
+
response.addResult(await renderRequest(req, res));
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
export async function renderRequest(request, response) {
|
|
79
|
+
const result = [];
|
|
80
|
+
// Basic request information (trimmed URL params for token efficiency)
|
|
81
|
+
const trimmedUrl = formatUrlWithTrimmedParams(request.url());
|
|
82
|
+
result.push(`[${request.method().toUpperCase()}] ${trimmedUrl}`);
|
|
83
|
+
// Append response status if available with compact content-type
|
|
84
|
+
if (response) {
|
|
85
|
+
const ct = response.headers()?.["content-type"];
|
|
86
|
+
result.push(`=> [${response.status()}] ${response.statusText()}${ct ? ` ct=${ct}` : ""}`);
|
|
87
|
+
}
|
|
88
|
+
// Always include request headers (excluding HTTP/2 pseudo-headers and common headers)
|
|
89
|
+
// const allHeaders = await request.allHeaders();
|
|
90
|
+
// const headers = Object.fromEntries(
|
|
91
|
+
// Object.entries(allHeaders).filter(([key]) => {
|
|
92
|
+
// const lowerKey = key.toLowerCase();
|
|
93
|
+
// // Filter out HTTP/2 pseudo-headers
|
|
94
|
+
// if (lowerKey.startsWith(':'))
|
|
95
|
+
// return false;
|
|
96
|
+
// // Filter out specified headers
|
|
97
|
+
// if (lowerKey === 'accept-encoding' ||
|
|
98
|
+
// lowerKey.startsWith('sec-') ||
|
|
99
|
+
// lowerKey.startsWith('sentry-') ||
|
|
100
|
+
// lowerKey === 'baggage' ||
|
|
101
|
+
// lowerKey === 'ect' ||
|
|
102
|
+
// lowerKey === 'connection' ||
|
|
103
|
+
// lowerKey === 'accept-language' ||
|
|
104
|
+
// lowerKey === 'priority' ||
|
|
105
|
+
// lowerKey === 'user-agent' ||
|
|
106
|
+
// lowerKey === 'upgrade-insecure-requests' ||
|
|
107
|
+
// lowerKey === 'cache-control')
|
|
108
|
+
// return false;
|
|
109
|
+
// return true;
|
|
110
|
+
// })
|
|
111
|
+
// );
|
|
112
|
+
// result.push(`headers=${JSON.stringify(headers)}`);
|
|
113
|
+
// Include raw body when method is not GET
|
|
114
|
+
// if (request.method().toUpperCase() !== 'GET') {
|
|
115
|
+
// const body = request.postData();
|
|
116
|
+
// if (body)
|
|
117
|
+
// result.push(`body=${body}`);
|
|
118
|
+
// }
|
|
119
|
+
return result.join("\n");
|
|
120
|
+
}
|
|
121
|
+
export default [requests];
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import ms from "ms";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { getNetworkEventEntry } from "../hooks/networkSetup.js";
|
|
4
|
+
import { extractGraphQLResponseInfo, minifyGraphQLQuery, minifyGraphQLRequestBody, parseGraphQLRequestFromHttp, summarizeGraphQL, } from "../utils/graphql.js";
|
|
5
|
+
import { formatNetworkSummaryLine } from "../utils/networkFormat.js";
|
|
6
|
+
import { sanitizeHtml } from "../utils/sanitizeHtml.js";
|
|
7
|
+
import { formatTruncationLine } from "../utils/truncate.js";
|
|
8
|
+
import { withTimeout } from "../utils/withTimeout.js";
|
|
9
|
+
import { defineTabTool } from "./tool.js";
|
|
10
|
+
const TIMEOUT_MS = ms("5s");
|
|
11
|
+
const CHUNK_BYTES = 8 * 1024; // 8KB per page
|
|
12
|
+
const contextBodyMap = new WeakMap();
|
|
13
|
+
// Skip HTTP/2 pseudo-headers and their non-colon variants in displayed request headers
|
|
14
|
+
const SKIP_REQUEST_HEADER_KEYS = new Set([
|
|
15
|
+
":authority",
|
|
16
|
+
":method",
|
|
17
|
+
":path",
|
|
18
|
+
":scheme",
|
|
19
|
+
"authority",
|
|
20
|
+
"method",
|
|
21
|
+
"path",
|
|
22
|
+
"scheme",
|
|
23
|
+
]);
|
|
24
|
+
const getStateMap = (ctx) => {
|
|
25
|
+
let m = contextBodyMap.get(ctx);
|
|
26
|
+
if (!m) {
|
|
27
|
+
m = new Map();
|
|
28
|
+
contextBodyMap.set(ctx, m);
|
|
29
|
+
}
|
|
30
|
+
return m;
|
|
31
|
+
};
|
|
32
|
+
const networkDetailSchema = z.object({
|
|
33
|
+
id: z.number().describe("The network event id from events log"),
|
|
34
|
+
});
|
|
35
|
+
const normalizeHeaderKeys = (headers) => {
|
|
36
|
+
const out = {};
|
|
37
|
+
for (const [k, v] of Object.entries(headers))
|
|
38
|
+
out[k.toLowerCase()] = v;
|
|
39
|
+
return out;
|
|
40
|
+
};
|
|
41
|
+
const formatBytes = (n) => {
|
|
42
|
+
const units = ["B", "KB", "MB", "GB"];
|
|
43
|
+
let i = 0;
|
|
44
|
+
let v = n;
|
|
45
|
+
while (v >= 1024 && i < units.length - 1) {
|
|
46
|
+
v /= 1024;
|
|
47
|
+
i++;
|
|
48
|
+
}
|
|
49
|
+
const digits = v < 10 && i > 0 ? 1 : 0;
|
|
50
|
+
return `${v.toFixed(digits)} ${units[i]}`;
|
|
51
|
+
};
|
|
52
|
+
const formatRequestDetail = async (ctx, { request, response, id, }) => {
|
|
53
|
+
const lines = [];
|
|
54
|
+
const reqHeaders = normalizeHeaderKeys(await request.allHeaders());
|
|
55
|
+
const requestBody = request.postData();
|
|
56
|
+
lines.push(formatNetworkSummaryLine({
|
|
57
|
+
method: request.method(),
|
|
58
|
+
url: request.url(),
|
|
59
|
+
status: response ? response.status() : 0,
|
|
60
|
+
statusText: response?.statusText(),
|
|
61
|
+
postData: requestBody,
|
|
62
|
+
headers: reqHeaders,
|
|
63
|
+
}, { trimParams: false }));
|
|
64
|
+
const timing = response ? response.request().timing() : null;
|
|
65
|
+
if (timing) {
|
|
66
|
+
const duration = Math.round(timing.responseEnd - timing.requestStart);
|
|
67
|
+
if (!Number.isNaN(duration))
|
|
68
|
+
lines.push(`Duration: ${duration}ms`);
|
|
69
|
+
}
|
|
70
|
+
lines.push(`Failure: ${request.failure()?.errorText || "None"}`);
|
|
71
|
+
if (!response) {
|
|
72
|
+
lines.push(`\nRequest Headers:`);
|
|
73
|
+
const headerKeysNoResp = Object.keys(reqHeaders)
|
|
74
|
+
.filter((k) => !SKIP_REQUEST_HEADER_KEYS.has(k))
|
|
75
|
+
.sort();
|
|
76
|
+
for (const key of headerKeysNoResp)
|
|
77
|
+
lines.push(`${key}: ${reqHeaders[key]}`);
|
|
78
|
+
lines.push(`\nNo response received yet`);
|
|
79
|
+
return lines.join("\n");
|
|
80
|
+
}
|
|
81
|
+
// Determine if this request is GraphQL (used for both request and response sections)
|
|
82
|
+
const gqlReq = parseGraphQLRequestFromHttp(request.method(), request.url(), reqHeaders, requestBody);
|
|
83
|
+
const map = getStateMap(ctx);
|
|
84
|
+
const existing = map.get(id);
|
|
85
|
+
let state;
|
|
86
|
+
if (!existing) {
|
|
87
|
+
state = { cursor: 0, headersShown: false, isGraphQLRequest: !!gqlReq };
|
|
88
|
+
map.set(id, state);
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
state = existing;
|
|
92
|
+
state.isGraphQLRequest = !!gqlReq;
|
|
93
|
+
}
|
|
94
|
+
// Headers printed once (first call)
|
|
95
|
+
if (!state.headersShown) {
|
|
96
|
+
// Print full request headers on the first call (excluding authority/method/path/scheme)
|
|
97
|
+
lines.push(`\nRequest Headers:`);
|
|
98
|
+
const headerKeys = Object.keys(reqHeaders)
|
|
99
|
+
.filter((k) => !SKIP_REQUEST_HEADER_KEYS.has(k))
|
|
100
|
+
.sort();
|
|
101
|
+
for (const key of headerKeys)
|
|
102
|
+
lines.push(`${key}: ${reqHeaders[key]}`);
|
|
103
|
+
const reqCt = reqHeaders["content-type"];
|
|
104
|
+
// GraphQL request summary (if applicable) and compact body handling
|
|
105
|
+
if (gqlReq) {
|
|
106
|
+
lines.push(`\nGraphQL Request: ${summarizeGraphQL(gqlReq)}`);
|
|
107
|
+
if (gqlReq.variables &&
|
|
108
|
+
typeof gqlReq.variables === "object" &&
|
|
109
|
+
!Array.isArray(gqlReq.variables)) {
|
|
110
|
+
const varKeys = Object.keys(gqlReq.variables);
|
|
111
|
+
if (varKeys.length)
|
|
112
|
+
lines.push(`Variables: { ${varKeys.join(", ")} }`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (requestBody) {
|
|
116
|
+
if (gqlReq) {
|
|
117
|
+
lines.push(`\nRequest Body (GraphQL):`);
|
|
118
|
+
try {
|
|
119
|
+
if (reqCt && reqCt.includes("application/graphql")) {
|
|
120
|
+
lines.push(minifyGraphQLQuery(requestBody));
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
const body = JSON.parse(requestBody);
|
|
124
|
+
const minimized = minifyGraphQLRequestBody(body);
|
|
125
|
+
lines.push(JSON.stringify(minimized, null, 2));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
lines.push(requestBody);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
lines.push(`\nRequest Body:`);
|
|
134
|
+
try {
|
|
135
|
+
lines.push(JSON.stringify(JSON.parse(requestBody), null, 2));
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
lines.push(requestBody);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const resHeaders = normalizeHeaderKeys(await response.allHeaders());
|
|
143
|
+
const resCt = resHeaders["content-type"];
|
|
144
|
+
const resCl = resHeaders["content-length"];
|
|
145
|
+
const headerParts = [];
|
|
146
|
+
if (resCt)
|
|
147
|
+
headerParts.push(`content-type=${resCt}`);
|
|
148
|
+
if (resCl)
|
|
149
|
+
headerParts.push(`content-length=${resCl}`);
|
|
150
|
+
if (headerParts.length)
|
|
151
|
+
lines.push(`\nResponse Headers: { ${headerParts.join(", ")} }`);
|
|
152
|
+
const setCookieHeaders = await response
|
|
153
|
+
.headerValues("set-cookie")
|
|
154
|
+
.catch(() => []);
|
|
155
|
+
if (setCookieHeaders.length) {
|
|
156
|
+
lines.push(`\nSet-Cookie Headers (${setCookieHeaders.length}):`);
|
|
157
|
+
for (const cookie of setCookieHeaders)
|
|
158
|
+
lines.push(cookie);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// Fetch the full body each time
|
|
162
|
+
let buf;
|
|
163
|
+
try {
|
|
164
|
+
buf = await withTimeout(response.body(), TIMEOUT_MS);
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
168
|
+
lines.push(`\nFailed to read response body: ${msg}`);
|
|
169
|
+
return lines.join("\n");
|
|
170
|
+
}
|
|
171
|
+
// On first page, summarize GraphQL response if applicable
|
|
172
|
+
if (!state.headersShown && state.isGraphQLRequest) {
|
|
173
|
+
try {
|
|
174
|
+
const fullText = buf.toString("utf8");
|
|
175
|
+
const gqlInfo = extractGraphQLResponseInfo(fullText);
|
|
176
|
+
if (gqlInfo) {
|
|
177
|
+
lines.push(`\nGraphQL Response: ${gqlInfo.hasErrors ? `${gqlInfo.errorCount} error(s)` : "ok"}`);
|
|
178
|
+
if (gqlInfo.topMessages.length)
|
|
179
|
+
lines.push(`Errors: ${gqlInfo.topMessages.join(" | ")}`);
|
|
180
|
+
if (gqlInfo.dataKeys.length)
|
|
181
|
+
lines.push(`Data keys: ${gqlInfo.dataKeys.join(", ")}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
catch { }
|
|
185
|
+
}
|
|
186
|
+
let bodyText = buf.toString("utf8");
|
|
187
|
+
const resHeadersForBody = normalizeHeaderKeys(await response.allHeaders());
|
|
188
|
+
const resCtForBody = resHeadersForBody["content-type"] || "";
|
|
189
|
+
const isHtml = resCtForBody.includes("html");
|
|
190
|
+
if (isHtml)
|
|
191
|
+
bodyText = sanitizeHtml(bodyText, {
|
|
192
|
+
shouldRemoveScripts: false,
|
|
193
|
+
shouldRemoveStyles: true,
|
|
194
|
+
});
|
|
195
|
+
const totalLength = bodyText.length;
|
|
196
|
+
if (state.cursor >= totalLength) {
|
|
197
|
+
state.cursor = 0;
|
|
198
|
+
state.headersShown = false; // allow headers again after a full pass
|
|
199
|
+
}
|
|
200
|
+
const start = state.cursor;
|
|
201
|
+
const end = Math.min(start + CHUNK_BYTES, totalLength);
|
|
202
|
+
const chunk = bodyText.slice(start, end);
|
|
203
|
+
const nextCursor = end;
|
|
204
|
+
const more = nextCursor < totalLength;
|
|
205
|
+
const percent = totalLength
|
|
206
|
+
? Math.round((nextCursor / totalLength) * 100)
|
|
207
|
+
: 100;
|
|
208
|
+
lines.push(`\nBody Chunk (text): ${percent}%${more ? " (more)" : " (done)"}:`);
|
|
209
|
+
lines.push(chunk);
|
|
210
|
+
if (more)
|
|
211
|
+
lines.push(formatTruncationLine(nextCursor, totalLength, { formatter: formatBytes }));
|
|
212
|
+
state.cursor = nextCursor;
|
|
213
|
+
state.headersShown = true;
|
|
214
|
+
return lines.join("\n");
|
|
215
|
+
};
|
|
216
|
+
const networkDetail = defineTabTool({
|
|
217
|
+
capability: "core",
|
|
218
|
+
schema: {
|
|
219
|
+
name: "browser_network_detail",
|
|
220
|
+
title: "Get network request detail",
|
|
221
|
+
description: "Show detailed info for a specific network request by event id. Call repeatedly to page through the body.",
|
|
222
|
+
inputSchema: networkDetailSchema,
|
|
223
|
+
type: "readOnly",
|
|
224
|
+
},
|
|
225
|
+
handle: async (tab, params, r) => {
|
|
226
|
+
const entry = getNetworkEventEntry(tab.context, params.id);
|
|
227
|
+
if (!entry) {
|
|
228
|
+
r.addResult(`Network request with ID ${params.id} not found`);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
r.addResult(await formatRequestDetail(tab.context, {
|
|
232
|
+
request: entry.request,
|
|
233
|
+
response: entry.response,
|
|
234
|
+
id: params.id,
|
|
235
|
+
}));
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
export default [networkDetail];
|