@wordbricks/playwright-mcp 0.1.25 → 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.
Files changed (82) hide show
  1. package/lib/browserContextFactory.js +399 -0
  2. package/lib/browserServerBackend.js +86 -0
  3. package/lib/config.js +300 -0
  4. package/lib/context.js +311 -0
  5. package/lib/extension/cdpRelay.js +352 -0
  6. package/lib/extension/extensionContextFactory.js +56 -0
  7. package/lib/frameworkPatterns.js +35 -0
  8. package/lib/hooks/antiBotDetectionHook.js +178 -0
  9. package/lib/hooks/core.js +145 -0
  10. package/lib/hooks/eventConsumer.js +52 -0
  11. package/lib/hooks/events.js +42 -0
  12. package/lib/hooks/formatToolCallEvent.js +12 -0
  13. package/lib/hooks/frameworkStateHook.js +182 -0
  14. package/lib/hooks/grouping.js +72 -0
  15. package/lib/hooks/jsonLdDetectionHook.js +182 -0
  16. package/lib/hooks/networkFilters.js +82 -0
  17. package/lib/hooks/networkSetup.js +61 -0
  18. package/lib/hooks/networkTrackingHook.js +67 -0
  19. package/lib/hooks/pageHeightHook.js +75 -0
  20. package/lib/hooks/registry.js +41 -0
  21. package/lib/hooks/requireTabHook.js +26 -0
  22. package/lib/hooks/schema.js +89 -0
  23. package/lib/hooks/waitHook.js +33 -0
  24. package/lib/index.js +41 -0
  25. package/lib/mcp/inProcessTransport.js +71 -0
  26. package/lib/mcp/proxyBackend.js +130 -0
  27. package/lib/mcp/server.js +91 -0
  28. package/lib/mcp/tool.js +44 -0
  29. package/lib/mcp/transport.js +188 -0
  30. package/lib/playwrightTransformer.js +520 -0
  31. package/lib/program.js +112 -0
  32. package/lib/response.js +192 -0
  33. package/lib/sessionLog.js +123 -0
  34. package/lib/tab.js +251 -0
  35. package/lib/tools/common.js +55 -0
  36. package/lib/tools/console.js +33 -0
  37. package/lib/tools/dialogs.js +50 -0
  38. package/lib/tools/evaluate.js +62 -0
  39. package/lib/tools/extractFrameworkState.js +225 -0
  40. package/lib/tools/files.js +48 -0
  41. package/lib/tools/form.js +66 -0
  42. package/lib/tools/getSnapshot.js +36 -0
  43. package/lib/tools/getVisibleHtml.js +68 -0
  44. package/lib/tools/install.js +51 -0
  45. package/lib/tools/keyboard.js +83 -0
  46. package/lib/tools/mouse.js +97 -0
  47. package/lib/tools/navigate.js +66 -0
  48. package/lib/tools/network.js +121 -0
  49. package/lib/tools/networkDetail.js +238 -0
  50. package/lib/tools/networkSearch/bodySearch.js +161 -0
  51. package/lib/tools/networkSearch/grouping.js +37 -0
  52. package/lib/tools/networkSearch/helpers.js +32 -0
  53. package/lib/tools/networkSearch/searchHtml.js +76 -0
  54. package/lib/tools/networkSearch/types.js +1 -0
  55. package/lib/tools/networkSearch/urlSearch.js +124 -0
  56. package/lib/tools/networkSearch.js +278 -0
  57. package/lib/tools/pdf.js +41 -0
  58. package/lib/tools/repl.js +414 -0
  59. package/lib/tools/screenshot.js +103 -0
  60. package/lib/tools/scroll.js +131 -0
  61. package/lib/tools/snapshot.js +161 -0
  62. package/lib/tools/tabs.js +62 -0
  63. package/lib/tools/tool.js +35 -0
  64. package/lib/tools/utils.js +78 -0
  65. package/lib/tools/wait.js +60 -0
  66. package/lib/tools.js +68 -0
  67. package/lib/utils/adBlockFilter.js +90 -0
  68. package/lib/utils/codegen.js +55 -0
  69. package/lib/utils/extensionPath.js +10 -0
  70. package/lib/utils/fileUtils.js +40 -0
  71. package/lib/utils/graphql.js +269 -0
  72. package/lib/utils/guid.js +22 -0
  73. package/lib/utils/httpServer.js +39 -0
  74. package/lib/utils/log.js +21 -0
  75. package/lib/utils/manualPromise.js +111 -0
  76. package/lib/utils/networkFormat.js +14 -0
  77. package/lib/utils/package.js +20 -0
  78. package/lib/utils/result.js +2 -0
  79. package/lib/utils/sanitizeHtml.js +130 -0
  80. package/lib/utils/truncate.js +103 -0
  81. package/lib/utils/withTimeout.js +7 -0
  82. package/package.json +11 -1
@@ -0,0 +1,278 @@
1
+ import { z } from "zod";
2
+ import { normalizeUrlForGrouping } from "../hooks/networkFilters.js";
3
+ import { getNetworkEventEntry } from "../hooks/networkSetup.js";
4
+ import { listNetworkEvents } from "../hooks/networkTrackingHook.js";
5
+ import { formatNetworkSummaryLine } from "../utils/networkFormat.js";
6
+ import { toJsonPathNormalized, truncateStringTo } from "../utils/truncate.js";
7
+ import { searchInRequestBody, searchInResponseBody, } from "./networkSearch/bodySearch.js";
8
+ import { getDepth, mergeGroupedMatches, normalizePath, } from "./networkSearch/grouping.js";
9
+ import { highlightMatch, parseKeywordParams } from "./networkSearch/helpers.js";
10
+ import { searchInUrls } from "./networkSearch/urlSearch.js";
11
+ import { defineTool } from "./tool.js";
12
+ const MAX_SEARCH_RESULTS = 10;
13
+ const MAX_GROUPS_TO_SHOW = 3;
14
+ const networkSearchSchema = z.object({
15
+ keyword: z
16
+ .string()
17
+ .describe("Keyword or phrase; avoid generic words—specific terms reduce noise and improve precision."),
18
+ });
19
+ const createSourceCounts = () => ({
20
+ requestUrl: 0,
21
+ requestBody: 0,
22
+ responseUrl: 0,
23
+ responseBody: 0,
24
+ responseHeaders: 0,
25
+ });
26
+ const accumulateSourceCounts = (records) => {
27
+ const counts = createSourceCounts();
28
+ for (const record of records)
29
+ counts[record.source] += 1;
30
+ return counts;
31
+ };
32
+ const cloneSourceCounts = (counts) => ({
33
+ requestUrl: counts.requestUrl,
34
+ requestBody: counts.requestBody,
35
+ responseUrl: counts.responseUrl,
36
+ responseBody: counts.responseBody,
37
+ responseHeaders: counts.responseHeaders,
38
+ });
39
+ const computeEventScore = (match) => {
40
+ const ageMs = Math.max(0, Date.now() - match.timestamp);
41
+ const recencyWindowMs = 10 * 60 * 1000;
42
+ const recencyBoost = 1 - Math.min(ageMs / recencyWindowMs, 1);
43
+ const base = match.totalMatches;
44
+ const responseBonus = match.sourceCounts.responseBody * 2;
45
+ const requestBonus = match.sourceCounts.requestBody;
46
+ const urlBonus = (match.sourceCounts.requestUrl + match.sourceCounts.responseUrl) * 0.25;
47
+ const headerBonus = match.sourceCounts.responseHeaders;
48
+ return (base + responseBonus + requestBonus + urlBonus + headerBonus + recencyBoost);
49
+ };
50
+ const formatGroupPath = (group) => {
51
+ const normalized = group.normalized;
52
+ const jsonPath = toJsonPathNormalized(normalized);
53
+ if (jsonPath)
54
+ return `json: ${jsonPath.jsonPath}`;
55
+ if (!normalized.includes(" > "))
56
+ return normalized;
57
+ const withoutWildcard = normalized.replace(/:nth-child\(\*\)/g, "");
58
+ const trimmedPrefix = withoutWildcard.startsWith("response.body")
59
+ ? withoutWildcard.slice("response.body".length).trim()
60
+ : withoutWildcard.startsWith("request.body")
61
+ ? withoutWildcard.slice("request.body".length).trim()
62
+ : withoutWildcard;
63
+ const noLeadingArrow = trimmedPrefix.startsWith(">")
64
+ ? trimmedPrefix.slice(1).trim()
65
+ : trimmedPrefix;
66
+ return `css: ${noLeadingArrow}`;
67
+ };
68
+ const extractExamples = (group) => {
69
+ const items = [];
70
+ for (const example of group.examples) {
71
+ const raw = example.value ?? example.context;
72
+ if (!raw)
73
+ continue;
74
+ const trimmed = raw.trim();
75
+ const base = trimmed.length > 0 ? trimmed : raw;
76
+ const { text } = truncateStringTo(base, 160);
77
+ if (!items.includes(text))
78
+ items.push(text);
79
+ }
80
+ return items;
81
+ };
82
+ const searchInResponseSetCookies = async (response, keyword, matches) => {
83
+ const cookies = await response.headerValues("set-cookie").catch(() => []);
84
+ if (!cookies.length)
85
+ return;
86
+ for (const [index, cookie] of cookies.entries()) {
87
+ if (!cookie.toLowerCase().includes(keyword))
88
+ continue;
89
+ matches.push({
90
+ path: `response.headers.set-cookie[${index}]`,
91
+ value: cookie,
92
+ context: highlightMatch(cookie, keyword, 120),
93
+ source: "responseHeaders",
94
+ });
95
+ }
96
+ };
97
+ const networkSearch = defineTool({
98
+ capability: "core",
99
+ schema: {
100
+ name: "browser_network_search",
101
+ title: "Search network requests",
102
+ description: "Search for keywords in network request/response bodies and URLs",
103
+ inputSchema: networkSearchSchema,
104
+ type: "readOnly",
105
+ },
106
+ handle: async (context, params, response) => {
107
+ await context.ensureTab();
108
+ try {
109
+ const keyword = params.keyword?.toLowerCase();
110
+ if (!keyword) {
111
+ response.addResult("keyword parameter is required");
112
+ return;
113
+ }
114
+ const events = listNetworkEvents(context);
115
+ const keywordParams = parseKeywordParams(params.keyword);
116
+ const searchMatches = [];
117
+ for (const ev of events) {
118
+ const entry = getNetworkEventEntry(context, ev.id);
119
+ if (!entry)
120
+ continue;
121
+ const request = entry.request;
122
+ const resp = entry.response ?? null;
123
+ const matches = [];
124
+ searchInUrls(request, resp, keyword, keywordParams, matches);
125
+ searchInRequestBody(request, keyword, matches);
126
+ if (resp) {
127
+ await searchInResponseBody(resp, keyword, matches);
128
+ await searchInResponseSetCookies(resp, keyword, matches);
129
+ }
130
+ if (matches.length > 0) {
131
+ const groupMap = new Map();
132
+ for (const m of matches) {
133
+ const normalized = normalizePath(m.path);
134
+ let group = groupMap.get(normalized);
135
+ if (!group) {
136
+ group = { normalized, count: 0, examples: [] };
137
+ groupMap.set(normalized, group);
138
+ }
139
+ group.count++;
140
+ if (group.examples.length < 3) {
141
+ const example = {
142
+ context: m.context,
143
+ value: m.value,
144
+ originalPath: m.path !== normalized ? m.path : undefined,
145
+ };
146
+ if (!group.examples.some((e) => e.context === example.context))
147
+ group.examples.push(example);
148
+ }
149
+ }
150
+ const groups = Array.from(groupMap.values()).sort((a, b) => b.count - a.count ||
151
+ getDepth(b.normalized) - getDepth(a.normalized));
152
+ const totalMatches = matches.length;
153
+ const sourceCounts = accumulateSourceCounts(matches);
154
+ searchMatches.push({
155
+ requestId: ev.id,
156
+ timestamp: ev.timestamp,
157
+ count: 1,
158
+ groups,
159
+ totalMatches,
160
+ sourceCounts,
161
+ request,
162
+ response: resp,
163
+ });
164
+ }
165
+ }
166
+ if (searchMatches.length === 0) {
167
+ response.addResult(`No network requests found containing keyword: "${params.keyword}"`);
168
+ return;
169
+ }
170
+ const aggMap = new Map();
171
+ for (const m of searchMatches) {
172
+ const key = `${m.request.method().toUpperCase()} ${normalizeUrlForGrouping(m.request.url())}`;
173
+ const existing = aggMap.get(key);
174
+ const eventScore = computeEventScore(m);
175
+ if (!existing) {
176
+ aggMap.set(key, {
177
+ key,
178
+ request: m.request,
179
+ response: m.response,
180
+ ids: [m.requestId],
181
+ count: m.count,
182
+ totalMatches: m.totalMatches,
183
+ groups: [...m.groups],
184
+ primaryGroups: m.groups,
185
+ primaryEventId: m.requestId,
186
+ primaryTimestamp: m.timestamp,
187
+ primarySourceCounts: cloneSourceCounts(m.sourceCounts),
188
+ primaryMatches: m.totalMatches,
189
+ primaryScore: eventScore,
190
+ });
191
+ continue;
192
+ }
193
+ existing.ids.push(m.requestId);
194
+ existing.count += m.count;
195
+ existing.totalMatches += m.totalMatches;
196
+ existing.groups = mergeGroupedMatches(existing.groups, m.groups);
197
+ if (!existing.response && m.response)
198
+ existing.response = m.response;
199
+ const replacePrimary = eventScore > existing.primaryScore ||
200
+ (eventScore === existing.primaryScore &&
201
+ m.timestamp > existing.primaryTimestamp);
202
+ if (!replacePrimary)
203
+ continue;
204
+ existing.request = m.request;
205
+ existing.response = m.response;
206
+ existing.primaryGroups = m.groups;
207
+ existing.primaryEventId = m.requestId;
208
+ existing.primaryTimestamp = m.timestamp;
209
+ existing.primarySourceCounts = cloneSourceCounts(m.sourceCounts);
210
+ existing.primaryMatches = m.totalMatches;
211
+ existing.primaryScore = eventScore;
212
+ }
213
+ const aggregatedMatches = Array.from(aggMap.values()).sort((a, b) => {
214
+ if (a.primaryScore !== b.primaryScore)
215
+ return b.primaryScore - a.primaryScore;
216
+ if (a.primaryMatches !== b.primaryMatches)
217
+ return b.primaryMatches - a.primaryMatches;
218
+ return b.primaryTimestamp - a.primaryTimestamp;
219
+ });
220
+ const topMatches = aggregatedMatches.slice(0, MAX_SEARCH_RESULTS);
221
+ const structured = {
222
+ keyword: params.keyword,
223
+ requests: topMatches.map((m) => {
224
+ const method = m.request.method().toUpperCase();
225
+ const url = m.request.url();
226
+ // Normalize URL for grouping only; not returned in output
227
+ const status = m.response ? m.response.status() : undefined;
228
+ const queryKeys = (() => {
229
+ try {
230
+ const u = new URL(url);
231
+ const keys = new Set();
232
+ u.searchParams.forEach((_, k) => {
233
+ if (k)
234
+ keys.add(k);
235
+ });
236
+ return Array.from(keys);
237
+ }
238
+ catch {
239
+ return [];
240
+ }
241
+ })();
242
+ const primaryGroups = m.primaryGroups
243
+ .slice()
244
+ .sort((a, b) => b.count - a.count ||
245
+ getDepth(b.normalized) - getDepth(a.normalized))
246
+ .slice(0, MAX_GROUPS_TO_SHOW);
247
+ const paths = primaryGroups.map((group) => ({
248
+ path: formatGroupPath(group),
249
+ examples: extractExamples(group),
250
+ }));
251
+ const sourceCounts = cloneSourceCounts(m.primarySourceCounts);
252
+ const score = Number(m.primaryScore.toFixed(2));
253
+ return {
254
+ summary: formatNetworkSummaryLine({
255
+ method,
256
+ url,
257
+ status: status || 0,
258
+ statusText: m.response?.statusText(),
259
+ postData: m.request.postData(),
260
+ headers: {},
261
+ }),
262
+ primaryEventId: m.primaryEventId,
263
+ eventIds: m.ids.slice(0, 5),
264
+ score,
265
+ sourceCounts,
266
+ params: queryKeys.slice(0, 6),
267
+ paths,
268
+ };
269
+ }),
270
+ };
271
+ response.addResult(JSON.stringify(structured));
272
+ }
273
+ catch (error) {
274
+ response.addResult(`Failed to search network requests: ${error.message}`);
275
+ }
276
+ },
277
+ });
278
+ export default [networkSearch];
@@ -0,0 +1,41 @@
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 { defineTabTool } from "./tool.js";
19
+ const pdfSchema = z.object({
20
+ filename: z
21
+ .string()
22
+ .optional()
23
+ .describe("File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified."),
24
+ });
25
+ const pdf = defineTabTool({
26
+ capability: "pdf",
27
+ schema: {
28
+ name: "browser_pdf_save",
29
+ title: "Save as PDF",
30
+ description: "Save page as PDF",
31
+ inputSchema: pdfSchema,
32
+ type: "readOnly",
33
+ },
34
+ handle: async (tab, params, response) => {
35
+ const fileName = await tab.context.outputFile(params.filename ?? `page-${new Date().toISOString()}.pdf`);
36
+ response.addCode(`await page.pdf(${javascript.formatObject({ path: fileName })});`);
37
+ response.addResult(`Saved page as ${fileName}`);
38
+ await tab.page.pdf({ path: fileName });
39
+ },
40
+ });
41
+ export default [pdf];