@wordbricks/playwright-mcp 0.1.3

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/LICENSE +202 -0
  2. package/README.md +624 -0
  3. package/cli-wrapper.js +47 -0
  4. package/cli.js +18 -0
  5. package/config.d.ts +119 -0
  6. package/index.d.ts +23 -0
  7. package/index.js +19 -0
  8. package/lib/browserContextFactory.js +289 -0
  9. package/lib/browserServerBackend.js +82 -0
  10. package/lib/config.js +246 -0
  11. package/lib/context.js +236 -0
  12. package/lib/extension/cdpRelay.js +346 -0
  13. package/lib/extension/extensionContextFactory.js +56 -0
  14. package/lib/frameworkPatterns.js +35 -0
  15. package/lib/hooks/core.js +144 -0
  16. package/lib/hooks/eventConsumer.js +39 -0
  17. package/lib/hooks/events.js +42 -0
  18. package/lib/hooks/formatToolCallEvent.js +16 -0
  19. package/lib/hooks/frameworkStateHook.js +182 -0
  20. package/lib/hooks/grouping.js +72 -0
  21. package/lib/hooks/jsonLdDetectionHook.js +175 -0
  22. package/lib/hooks/networkFilters.js +74 -0
  23. package/lib/hooks/networkSetup.js +56 -0
  24. package/lib/hooks/networkTrackingHook.js +55 -0
  25. package/lib/hooks/pageHeightHook.js +75 -0
  26. package/lib/hooks/registry.js +39 -0
  27. package/lib/hooks/requireTabHook.js +26 -0
  28. package/lib/hooks/schema.js +75 -0
  29. package/lib/hooks/waitHook.js +33 -0
  30. package/lib/index.js +39 -0
  31. package/lib/loop/loop.js +69 -0
  32. package/lib/loop/loopClaude.js +152 -0
  33. package/lib/loop/loopOpenAI.js +141 -0
  34. package/lib/loop/main.js +60 -0
  35. package/lib/loopTools/context.js +66 -0
  36. package/lib/loopTools/main.js +51 -0
  37. package/lib/loopTools/perform.js +32 -0
  38. package/lib/loopTools/snapshot.js +29 -0
  39. package/lib/loopTools/tool.js +18 -0
  40. package/lib/mcp/inProcessTransport.js +72 -0
  41. package/lib/mcp/proxyBackend.js +115 -0
  42. package/lib/mcp/server.js +86 -0
  43. package/lib/mcp/tool.js +29 -0
  44. package/lib/mcp/transport.js +181 -0
  45. package/lib/playwrightTransformer.js +497 -0
  46. package/lib/program.js +111 -0
  47. package/lib/response.js +186 -0
  48. package/lib/sessionLog.js +121 -0
  49. package/lib/tab.js +249 -0
  50. package/lib/tools/common.js +55 -0
  51. package/lib/tools/console.js +33 -0
  52. package/lib/tools/dialogs.js +47 -0
  53. package/lib/tools/evaluate.js +53 -0
  54. package/lib/tools/extractFrameworkState.js +214 -0
  55. package/lib/tools/files.js +44 -0
  56. package/lib/tools/getSnapshot.js +37 -0
  57. package/lib/tools/getVisibleHtml.js +52 -0
  58. package/lib/tools/install.js +53 -0
  59. package/lib/tools/keyboard.js +78 -0
  60. package/lib/tools/mouse.js +99 -0
  61. package/lib/tools/navigate.js +70 -0
  62. package/lib/tools/network.js +123 -0
  63. package/lib/tools/networkDetail.js +231 -0
  64. package/lib/tools/networkSearch/bodySearch.js +141 -0
  65. package/lib/tools/networkSearch/grouping.js +28 -0
  66. package/lib/tools/networkSearch/helpers.js +32 -0
  67. package/lib/tools/networkSearch/searchHtml.js +65 -0
  68. package/lib/tools/networkSearch/types.js +1 -0
  69. package/lib/tools/networkSearch/urlSearch.js +82 -0
  70. package/lib/tools/networkSearch.js +168 -0
  71. package/lib/tools/pdf.js +40 -0
  72. package/lib/tools/repl.js +402 -0
  73. package/lib/tools/screenshot.js +79 -0
  74. package/lib/tools/scroll.js +126 -0
  75. package/lib/tools/snapshot.js +139 -0
  76. package/lib/tools/tabs.js +87 -0
  77. package/lib/tools/tool.js +33 -0
  78. package/lib/tools/utils.js +74 -0
  79. package/lib/tools/wait.js +55 -0
  80. package/lib/tools.js +67 -0
  81. package/lib/utils/codegen.js +49 -0
  82. package/lib/utils/extensionPath.js +6 -0
  83. package/lib/utils/fileUtils.js +36 -0
  84. package/lib/utils/graphql.js +258 -0
  85. package/lib/utils/guid.js +22 -0
  86. package/lib/utils/httpServer.js +39 -0
  87. package/lib/utils/log.js +21 -0
  88. package/lib/utils/manualPromise.js +111 -0
  89. package/lib/utils/networkFormat.js +12 -0
  90. package/lib/utils/package.js +20 -0
  91. package/lib/utils/result.js +2 -0
  92. package/lib/utils/sanitizeHtml.js +98 -0
  93. package/lib/utils/truncate.js +103 -0
  94. package/lib/utils/withTimeout.js +7 -0
  95. package/package.json +100 -0
@@ -0,0 +1,65 @@
1
+ import * as cheerio from 'cheerio';
2
+ import { highlightMatch } from './helpers.js';
3
+ export const getElementPath = ($el) => {
4
+ const path = [];
5
+ let current = $el;
6
+ while (current.length && current[0].type === 'tag' && current[0].name !== 'html') {
7
+ let selector = current[0].name.toLowerCase();
8
+ const id = current.attr('id');
9
+ if (id) {
10
+ selector += `#${id}`;
11
+ path.unshift(selector);
12
+ break;
13
+ }
14
+ const classes = current.attr('class');
15
+ if (classes)
16
+ selector += `.${classes.trim().split(/\s+/).join('.')}`;
17
+ const tagName = current[0].type === 'tag' ? current[0].name : '';
18
+ const siblings = current.parent().children().filter((_, el) => el.type === 'tag' && el.name === tagName);
19
+ if (siblings.length > 1) {
20
+ const index = siblings.index(current) + 1;
21
+ selector += `:nth-child(${index})`;
22
+ }
23
+ path.unshift(selector);
24
+ current = current.parent();
25
+ }
26
+ return path.join(' > ');
27
+ };
28
+ export const searchInHtml = (html, keyword, basePath, matches) => {
29
+ const $ = cheerio.load(html);
30
+ $('*').contents().each((_, node) => {
31
+ if (node.type === 'text') {
32
+ const text = (node.data || '').trim();
33
+ if (text && text.toLowerCase().includes(keyword)) {
34
+ const parent = $(node).parent();
35
+ if (parent.length) {
36
+ const elPath = getElementPath(parent);
37
+ const path = elPath ? `${basePath} > ${elPath}` : basePath;
38
+ matches.push({
39
+ path,
40
+ value: text,
41
+ context: highlightMatch(text, keyword, 300),
42
+ });
43
+ }
44
+ }
45
+ }
46
+ });
47
+ $('*').each((_, el) => {
48
+ if (el.type === 'tag') {
49
+ const attrs = el.attribs;
50
+ if (attrs) {
51
+ Object.entries(attrs).forEach(([key, val]) => {
52
+ if (typeof val === 'string' && val.toLowerCase().includes(keyword)) {
53
+ const elPath = getElementPath($(el));
54
+ const path = elPath ? `${basePath} > ${elPath}@${key}` : `${basePath}@${key}`;
55
+ matches.push({
56
+ path,
57
+ value: val,
58
+ context: highlightMatch(val, keyword, 300),
59
+ });
60
+ }
61
+ });
62
+ }
63
+ }
64
+ });
65
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,82 @@
1
+ import { highlightMatch } from './helpers.js';
2
+ const CONTEXT_LENGTH_DEFAULT = 300;
3
+ export const searchInUrls = (request, response, keyword, keywordParams, matches) => {
4
+ try {
5
+ const reqUrl = request.url();
6
+ const reqUrlLower = reqUrl.toLowerCase();
7
+ const keywordPathOnly = keyword.split('?')[0];
8
+ if (reqUrlLower.includes(keyword)) {
9
+ matches.push({ path: 'request.url', value: reqUrl, context: `url: ${highlightMatch(reqUrl, keyword, CONTEXT_LENGTH_DEFAULT)}` });
10
+ }
11
+ else if (keywordPathOnly && reqUrlLower.includes(keywordPathOnly)) {
12
+ matches.push({ path: 'request.url', value: reqUrl, context: `url: ${highlightMatch(reqUrl, keywordPathOnly, CONTEXT_LENGTH_DEFAULT)}` });
13
+ }
14
+ else {
15
+ try {
16
+ const u = new URL(reqUrl);
17
+ const pathnameLower = u.pathname.toLowerCase();
18
+ if (pathnameLower.includes(keyword) || (keywordPathOnly && pathnameLower.includes(keywordPathOnly)))
19
+ matches.push({ path: 'request.url', value: reqUrl, context: `url: ${highlightMatch(reqUrl, keywordPathOnly || keyword, CONTEXT_LENGTH_DEFAULT)}` });
20
+ }
21
+ catch { }
22
+ }
23
+ if (keywordParams.length) {
24
+ try {
25
+ const u = new URL(reqUrl);
26
+ for (const { name, value } of keywordParams) {
27
+ if (!name)
28
+ continue;
29
+ const pageVal = u.searchParams.get(name);
30
+ if (!pageVal)
31
+ continue;
32
+ const valLower = (value || '').toLowerCase();
33
+ if (!valLower)
34
+ continue;
35
+ const pageValLower = pageVal.toLowerCase();
36
+ if (pageValLower.includes(valLower))
37
+ matches.push({ path: `request.url.query.${name}`, value: pageVal, context: `${name}=${highlightMatch(pageVal, value, CONTEXT_LENGTH_DEFAULT)}` });
38
+ }
39
+ }
40
+ catch { }
41
+ }
42
+ if (response) {
43
+ const resUrl = response.url();
44
+ const resUrlLower = resUrl.toLowerCase();
45
+ if (resUrlLower.includes(keyword)) {
46
+ matches.push({ path: 'response.url', value: resUrl, context: `url: ${highlightMatch(resUrl, keyword, CONTEXT_LENGTH_DEFAULT)}` });
47
+ }
48
+ else if (keywordPathOnly && resUrlLower.includes(keywordPathOnly)) {
49
+ matches.push({ path: 'response.url', value: resUrl, context: `url: ${highlightMatch(resUrl, keywordPathOnly, CONTEXT_LENGTH_DEFAULT)}` });
50
+ }
51
+ else {
52
+ try {
53
+ const u2 = new URL(resUrl);
54
+ const pathnameLower2 = u2.pathname.toLowerCase();
55
+ if (pathnameLower2.includes(keyword) || (keywordPathOnly && pathnameLower2.includes(keywordPathOnly)))
56
+ matches.push({ path: 'response.url', value: resUrl, context: `url: ${highlightMatch(resUrl, keywordPathOnly || keyword, CONTEXT_LENGTH_DEFAULT)}` });
57
+ }
58
+ catch { }
59
+ }
60
+ if (keywordParams.length) {
61
+ try {
62
+ const u2 = new URL(resUrl);
63
+ for (const { name, value } of keywordParams) {
64
+ if (!name)
65
+ continue;
66
+ const pageVal = u2.searchParams.get(name);
67
+ if (!pageVal)
68
+ continue;
69
+ const valLower = (value || '').toLowerCase();
70
+ if (!valLower)
71
+ continue;
72
+ const pageValLower = pageVal.toLowerCase();
73
+ if (pageValLower.includes(valLower))
74
+ matches.push({ path: `response.url.query.${name}`, value: pageVal, context: `${name}=${highlightMatch(pageVal, value, CONTEXT_LENGTH_DEFAULT)}` });
75
+ }
76
+ }
77
+ catch { }
78
+ }
79
+ }
80
+ }
81
+ catch { }
82
+ };
@@ -0,0 +1,168 @@
1
+ import { z } from 'zod';
2
+ import { defineTool } from './tool.js';
3
+ import { getNetworkEventEntry } from '../hooks/networkSetup.js';
4
+ import { listNetworkEvents } from '../hooks/networkTrackingHook.js';
5
+ import { normalizeUrlForGrouping } from '../hooks/networkFilters.js';
6
+ import { formatNetworkSummaryLine } from '../utils/networkFormat.js';
7
+ import { toJsonPathNormalized } from '../utils/truncate.js';
8
+ import { searchInUrls } from './networkSearch/urlSearch.js';
9
+ import { searchInRequestBody, searchInResponseBody } from './networkSearch/bodySearch.js';
10
+ import { normalizePath, getDepth, mergeGroupedMatches } from './networkSearch/grouping.js';
11
+ import { parseKeywordParams } from './networkSearch/helpers.js';
12
+ const MAX_SEARCH_RESULTS = 10;
13
+ const MAX_GROUPS_TO_SHOW = 3;
14
+ const networkSearchSchema = z.object({
15
+ keyword: z.string().describe('Keyword or phrase; avoid generic words—specific terms reduce noise and improve precision.'),
16
+ });
17
+ const networkSearch = defineTool({
18
+ capability: 'core',
19
+ schema: {
20
+ name: 'browser_network_search',
21
+ title: 'Search network requests',
22
+ description: 'Search for keywords in network request/response bodies and URLs',
23
+ inputSchema: networkSearchSchema,
24
+ type: 'readOnly',
25
+ },
26
+ handle: async (context, params, response) => {
27
+ await context.ensureTab();
28
+ try {
29
+ const keyword = params.keyword?.toLowerCase();
30
+ if (!keyword) {
31
+ response.addResult('keyword parameter is required');
32
+ return;
33
+ }
34
+ const events = listNetworkEvents(context);
35
+ const keywordParams = parseKeywordParams(params.keyword);
36
+ const searchMatches = [];
37
+ for (const ev of events) {
38
+ const entry = getNetworkEventEntry(context, ev.id);
39
+ if (!entry)
40
+ continue;
41
+ const request = entry.request;
42
+ const resp = entry.response ?? null;
43
+ const matches = [];
44
+ searchInUrls(request, resp, keyword, keywordParams, matches);
45
+ searchInRequestBody(request, keyword, matches);
46
+ if (resp)
47
+ await searchInResponseBody(resp, keyword, matches);
48
+ if (matches.length > 0) {
49
+ const groupMap = new Map();
50
+ for (const m of matches) {
51
+ const normalized = normalizePath(m.path);
52
+ let group = groupMap.get(normalized);
53
+ if (!group) {
54
+ group = { normalized, count: 0, examples: [] };
55
+ groupMap.set(normalized, group);
56
+ }
57
+ group.count++;
58
+ if (group.examples.length < 3) {
59
+ const example = { context: m.context, value: m.value, originalPath: m.path !== normalized ? m.path : undefined };
60
+ if (!group.examples.some(e => e.context === example.context))
61
+ group.examples.push(example);
62
+ }
63
+ }
64
+ const groups = Array.from(groupMap.values()).sort((a, b) => b.count - a.count || getDepth(b.normalized) - getDepth(a.normalized));
65
+ const totalMatches = matches.length;
66
+ searchMatches.push({
67
+ requestId: ev.id,
68
+ count: 1,
69
+ groups,
70
+ totalMatches,
71
+ request,
72
+ response: resp,
73
+ });
74
+ }
75
+ }
76
+ if (searchMatches.length === 0) {
77
+ response.addResult(`No network requests found containing keyword: "${params.keyword}"`);
78
+ return;
79
+ }
80
+ const aggMap = new Map();
81
+ for (const m of searchMatches) {
82
+ const key = `${m.request.method().toUpperCase()} ${normalizeUrlForGrouping(m.request.url())}`;
83
+ const existing = aggMap.get(key);
84
+ if (!existing) {
85
+ aggMap.set(key, {
86
+ key,
87
+ request: m.request,
88
+ response: m.response,
89
+ ids: [m.requestId],
90
+ count: m.count,
91
+ totalMatches: m.totalMatches,
92
+ groups: [...m.groups],
93
+ });
94
+ }
95
+ else {
96
+ existing.ids.push(m.requestId);
97
+ existing.count += m.count;
98
+ existing.totalMatches += m.totalMatches;
99
+ existing.groups = mergeGroupedMatches(existing.groups, m.groups);
100
+ if (!existing.response && m.response)
101
+ existing.response = m.response;
102
+ }
103
+ }
104
+ const aggregatedMatches = Array.from(aggMap.values()).sort((a, b) => b.totalMatches - a.totalMatches);
105
+ const topMatches = aggregatedMatches.slice(0, MAX_SEARCH_RESULTS);
106
+ const structured = {
107
+ keyword: params.keyword,
108
+ requests: topMatches.map(m => {
109
+ const method = m.request.method().toUpperCase();
110
+ const url = m.request.url();
111
+ // Normalize URL for grouping only; not returned in output
112
+ const status = m.response ? m.response.status() : undefined;
113
+ const queryKeys = (() => {
114
+ try {
115
+ const u = new URL(url);
116
+ const keys = new Set();
117
+ u.searchParams.forEach((_, k) => {
118
+ if (k)
119
+ keys.add(k);
120
+ });
121
+ return Array.from(keys);
122
+ }
123
+ catch {
124
+ return [];
125
+ }
126
+ })();
127
+ const paths = m.groups
128
+ .sort((a, b) => b.count - a.count || getDepth(b.normalized) - getDepth(a.normalized))
129
+ .slice(0, MAX_GROUPS_TO_SHOW)
130
+ .map(g => {
131
+ const normJson = toJsonPathNormalized(g.normalized);
132
+ if (normJson)
133
+ return `json: ${normJson.jsonPath}`;
134
+ if (g.normalized.includes(' > ')) {
135
+ let cleaned = g.normalized.replace(/:nth-child\(\*\)/g, '');
136
+ if (cleaned.startsWith('response.body'))
137
+ cleaned = cleaned.slice('response.body'.length).trim();
138
+ else if (cleaned.startsWith('request.body'))
139
+ cleaned = cleaned.slice('request.body'.length).trim();
140
+ if (cleaned.startsWith('>'))
141
+ cleaned = cleaned.slice(1).trim();
142
+ return `css: ${cleaned}`;
143
+ }
144
+ return g.normalized;
145
+ });
146
+ return {
147
+ summary: formatNetworkSummaryLine({
148
+ method,
149
+ url,
150
+ status: status || 0,
151
+ statusText: m.response?.statusText(),
152
+ postData: m.request.postData(),
153
+ headers: {},
154
+ }),
155
+ eventIds: m.ids.slice(0, 5),
156
+ params: queryKeys.slice(0, 6),
157
+ paths,
158
+ };
159
+ })
160
+ };
161
+ response.addResult(JSON.stringify(structured));
162
+ }
163
+ catch (error) {
164
+ response.addResult(`Failed to search network requests: ${error.message}`);
165
+ }
166
+ },
167
+ });
168
+ export default [networkSearch];
@@ -0,0 +1,40 @@
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
+ import * as javascript from '../utils/codegen.js';
19
+ const pdfSchema = z.object({
20
+ filename: z.string().optional().describe('File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified.'),
21
+ });
22
+ const pdf = defineTabTool({
23
+ capability: 'pdf',
24
+ schema: {
25
+ name: 'browser_pdf_save',
26
+ title: 'Save as PDF',
27
+ description: 'Save page as PDF',
28
+ inputSchema: pdfSchema,
29
+ type: 'readOnly',
30
+ },
31
+ handle: async (tab, params, response) => {
32
+ const fileName = await tab.context.outputFile(params.filename ?? `page-${new Date().toISOString()}.pdf`);
33
+ response.addCode(`await page.pdf(${javascript.formatObject({ path: fileName })});`);
34
+ response.addResult(`Saved page as ${fileName}`);
35
+ await tab.page.pdf({ path: fileName });
36
+ },
37
+ });
38
+ export default [
39
+ pdf,
40
+ ];