mcp-browser-dev-tools 0.0.1-beta.9 → 0.0.2-beta.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/src/logger.mjs ADDED
@@ -0,0 +1,53 @@
1
+ import process from "node:process";
2
+
3
+ import { PACKAGE_NAME } from "./package-info.mjs";
4
+
5
+ export const LOG_LEVELS = {
6
+ error: 0,
7
+ warn: 1,
8
+ info: 2,
9
+ debug: 3,
10
+ };
11
+
12
+ function normalizeMessage(message) {
13
+ if (message instanceof Error) {
14
+ return message.message;
15
+ }
16
+
17
+ return String(message);
18
+ }
19
+
20
+ export function createLogger({
21
+ level = "error",
22
+ output = process.stderr,
23
+ name = PACKAGE_NAME,
24
+ } = {}) {
25
+ const threshold = LOG_LEVELS[level] ?? LOG_LEVELS.error;
26
+
27
+ return {
28
+ level,
29
+ enabled(messageLevel) {
30
+ return (LOG_LEVELS[messageLevel] ?? -1) <= threshold;
31
+ },
32
+ log(messageLevel, message, options = {}) {
33
+ if (!options.force && !this.enabled(messageLevel)) {
34
+ return false;
35
+ }
36
+
37
+ output.write(`[${name}] ${messageLevel}: ${normalizeMessage(message)}\n`);
38
+ return true;
39
+ },
40
+ error(message, options) {
41
+ return this.log("error", message, options);
42
+ },
43
+ warn(message, options) {
44
+ return this.log("warn", message, options);
45
+ },
46
+ info(message, options) {
47
+ return this.log("info", message, options);
48
+ },
49
+ debug(message, options) {
50
+ return this.log("debug", message, options);
51
+ },
52
+ };
53
+ }
@@ -1,9 +1,9 @@
1
1
  import { encodeMessage, MessageBuffer } from "./json-rpc-stdio.mjs";
2
+ import { createLogger } from "./logger.mjs";
2
3
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
3
4
 
4
5
  const SERVER_NAME = PACKAGE_NAME;
5
6
  const SERVER_VERSION = PACKAGE_VERSION;
6
- const DEBUG_STDIO_ENABLED = process.env.MCP_BROWSER_DEBUG_STDIO === "1";
7
7
 
8
8
  function formatChunkPreview(chunk, limit = 160) {
9
9
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
@@ -173,6 +173,68 @@ function waitUntilProperty() {
173
173
  };
174
174
  }
175
175
 
176
+ function waitForInputSchema() {
177
+ return {
178
+ type: "object",
179
+ properties: {
180
+ sessionId: {
181
+ type: "string",
182
+ },
183
+ selector: {
184
+ type: "string",
185
+ },
186
+ state: {
187
+ type: "string",
188
+ enum: ["present", "visible", "hidden"],
189
+ },
190
+ url: {
191
+ type: "string",
192
+ },
193
+ urlIncludes: {
194
+ type: "string",
195
+ },
196
+ readyState: {
197
+ type: "string",
198
+ enum: ["interactive", "complete"],
199
+ },
200
+ timeoutMs: {
201
+ type: "integer",
202
+ minimum: 1,
203
+ },
204
+ pollIntervalMs: {
205
+ type: "integer",
206
+ minimum: 1,
207
+ },
208
+ },
209
+ required: ["sessionId"],
210
+ additionalProperties: false,
211
+ };
212
+ }
213
+
214
+ function newTabInputSchema(browserFamily) {
215
+ const properties = {
216
+ url: {
217
+ type: "string",
218
+ },
219
+ };
220
+ const required = [];
221
+
222
+ if (browserFamily === "auto") {
223
+ properties.browserFamily = {
224
+ type: "string",
225
+ enum: ["chromium", "firefox"],
226
+ };
227
+ required.push("browserFamily");
228
+ }
229
+
230
+ return {
231
+ type: "object",
232
+ properties,
233
+ required,
234
+ additionalProperties: false,
235
+ };
236
+ }
237
+
176
238
  export class McpBrowserDevToolsServer {
177
239
  constructor({
178
240
  config,
@@ -180,12 +242,18 @@ export class McpBrowserDevToolsServer {
180
242
  input = process.stdin,
181
243
  output = process.stdout,
182
244
  errorOutput = process.stderr,
245
+ logger = createLogger({
246
+ level: config.logLevel,
247
+ output: errorOutput,
248
+ name: SERVER_NAME,
249
+ }),
183
250
  }) {
184
251
  this.config = config;
185
252
  this.browserAdapter = browserAdapter;
186
253
  this.input = input;
187
254
  this.output = output;
188
255
  this.errorOutput = errorOutput;
256
+ this.logger = logger;
189
257
  this.messageBuffer = new MessageBuffer();
190
258
  this.tools = this.createTools();
191
259
  }
@@ -201,7 +269,11 @@ export class McpBrowserDevToolsServer {
201
269
  "Report whether the configured browser endpoint is reachable and how many active sessions are attached.",
202
270
  inputSchema: emptyObjectSchema(),
203
271
  },
204
- handler: async () => this.browserAdapter.getBrowserStatus(),
272
+ handler: async () => ({
273
+ serverName: SERVER_NAME,
274
+ serverVersion: SERVER_VERSION,
275
+ ...(await this.browserAdapter.getBrowserStatus()),
276
+ }),
205
277
  },
206
278
  ],
207
279
  [
@@ -232,6 +304,43 @@ export class McpBrowserDevToolsServer {
232
304
  }),
233
305
  },
234
306
  ],
307
+ [
308
+ "new_tab",
309
+ {
310
+ definition: {
311
+ name: "new_tab",
312
+ description:
313
+ "Create a new browser tab and return the resulting target metadata.",
314
+ inputSchema: newTabInputSchema(this.config.browserFamily),
315
+ },
316
+ handler: async (args) =>
317
+ this.browserAdapter.createTab(args.url, {
318
+ browserFamily: args.browserFamily,
319
+ }),
320
+ },
321
+ ],
322
+ [
323
+ "close_tab",
324
+ {
325
+ definition: {
326
+ name: "close_tab",
327
+ description:
328
+ "Close a browser tab by target id. Any attached session for that tab will disconnect.",
329
+ inputSchema: {
330
+ type: "object",
331
+ properties: {
332
+ targetId: {
333
+ type: "string",
334
+ },
335
+ },
336
+ required: ["targetId"],
337
+ additionalProperties: false,
338
+ },
339
+ },
340
+ handler: async (args) =>
341
+ this.browserAdapter.closeTarget(args.targetId),
342
+ },
343
+ ],
235
344
  [
236
345
  "attach_tab",
237
346
  {
@@ -290,6 +399,43 @@ export class McpBrowserDevToolsServer {
290
399
  this.browserAdapter.getPageState(args.sessionId),
291
400
  },
292
401
  ],
402
+ [
403
+ "wait_for",
404
+ {
405
+ definition: {
406
+ name: "wait_for",
407
+ description:
408
+ "Wait for page state such as selector visibility, URL, or ready state on an attached session.",
409
+ inputSchema: waitForInputSchema(),
410
+ },
411
+ handler: async (args) => {
412
+ if (
413
+ !args.selector &&
414
+ !args.url &&
415
+ !args.urlIncludes &&
416
+ !args.readyState
417
+ ) {
418
+ throw new Error(
419
+ "wait_for requires at least one of selector, url, urlIncludes, or readyState",
420
+ );
421
+ }
422
+
423
+ if (!args.selector && args.state !== undefined) {
424
+ throw new Error("wait_for state requires selector");
425
+ }
426
+
427
+ return this.browserAdapter.waitFor(args.sessionId, {
428
+ selector: args.selector,
429
+ state: args.state,
430
+ url: args.url,
431
+ urlIncludes: args.urlIncludes,
432
+ readyState: args.readyState,
433
+ timeoutMs: args.timeoutMs,
434
+ pollIntervalMs: args.pollIntervalMs,
435
+ });
436
+ },
437
+ },
438
+ ],
293
439
  [
294
440
  "navigate",
295
441
  {
@@ -744,9 +890,11 @@ export class McpBrowserDevToolsServer {
744
890
 
745
891
  this.input.on("data", (chunk) => {
746
892
  sawInput = true;
747
- if (DEBUG_STDIO_ENABLED) {
748
- this.log(
893
+ if (this.config.debugStdio) {
894
+ this.logger.log(
895
+ "debug",
749
896
  `stdin chunk bytes=${chunk.length} preview="${formatChunkPreview(chunk)}"`,
897
+ { force: true },
750
898
  );
751
899
  }
752
900
 
@@ -754,7 +902,7 @@ export class McpBrowserDevToolsServer {
754
902
  try {
755
903
  messages = this.messageBuffer.push(chunk);
756
904
  } catch (error) {
757
- this.log(`failed to parse incoming message: ${error.message}`);
905
+ this.logger.error(`failed to parse incoming message: ${error.message}`);
758
906
  return;
759
907
  }
760
908
 
@@ -763,13 +911,17 @@ export class McpBrowserDevToolsServer {
763
911
  }
764
912
  });
765
913
 
766
- if (DEBUG_STDIO_ENABLED) {
914
+ if (this.config.debugStdio) {
767
915
  this.input.on("end", () => {
768
- this.log(`stdin ended after_input=${sawInput}`);
916
+ this.logger.log("debug", `stdin ended after_input=${sawInput}`, {
917
+ force: true,
918
+ });
769
919
  });
770
920
 
771
921
  this.input.on("close", () => {
772
- this.log(`stdin closed after_input=${sawInput}`);
922
+ this.logger.log("debug", `stdin closed after_input=${sawInput}`, {
923
+ force: true,
924
+ });
773
925
  });
774
926
  }
775
927
 
@@ -777,15 +929,11 @@ export class McpBrowserDevToolsServer {
777
929
  this.input.resume();
778
930
  }
779
931
 
780
- this.log(
932
+ this.logger.info(
781
933
  `listening on stdio for MCP messages; browser=${this.config.browserFamily}`,
782
934
  );
783
935
  }
784
936
 
785
- log(message) {
786
- this.errorOutput.write(`[${SERVER_NAME}] ${message}\n`);
787
- }
788
-
789
937
  async dispatch(message) {
790
938
  const response = await this.handleRequest(message);
791
939
  if (!response) {
package/src/tcp-relay.mjs CHANGED
@@ -3,6 +3,8 @@ import os from "node:os";
3
3
  import process from "node:process";
4
4
 
5
5
  import { isLoopbackHost, isTruthyFlag } from "./config.mjs";
6
+ import { createLogger } from "./logger.mjs";
7
+ import { PACKAGE_NAME } from "./package-info.mjs";
6
8
 
7
9
  export const DEFAULT_RELAY_LISTEN_HOST = "127.0.0.1";
8
10
  export const DEFAULT_RELAY_LISTEN_PORT = 9223;
@@ -129,6 +131,10 @@ export async function startTcpRelay({
129
131
  targetHost,
130
132
  targetPort,
131
133
  errorOutput = process.stderr,
134
+ logger = createLogger({
135
+ output: errorOutput,
136
+ name: PACKAGE_NAME,
137
+ }),
132
138
  } = {}) {
133
139
  const openSockets = new Set();
134
140
 
@@ -154,7 +160,7 @@ export async function startTcpRelay({
154
160
  });
155
161
 
156
162
  upstreamSocket.on("error", (error) => {
157
- errorOutput.write(`[relay] target connection failed: ${error.message}\n`);
163
+ logger.error(`relay target connection failed: ${error.message}`);
158
164
  clientSocket.destroy();
159
165
  });
160
166
 
@@ -0,0 +1,201 @@
1
+ function sleep(ms) {
2
+ return new Promise((resolve) => {
3
+ setTimeout(resolve, ms);
4
+ });
5
+ }
6
+
7
+ const READY_STATE_ORDER = {
8
+ loading: 0,
9
+ interactive: 1,
10
+ complete: 2,
11
+ };
12
+
13
+ function normalizeOptionalString(value) {
14
+ return typeof value === "string" && value.trim() ? value.trim() : null;
15
+ }
16
+
17
+ function normalizeSelectorState(value) {
18
+ if (value === "present" || value === "visible" || value === "hidden") {
19
+ return value;
20
+ }
21
+
22
+ return "visible";
23
+ }
24
+
25
+ function normalizeReadyState(value) {
26
+ if (value === "interactive" || value === "complete") {
27
+ return value;
28
+ }
29
+
30
+ return null;
31
+ }
32
+
33
+ function normalizeInteger(value, fallback) {
34
+ return Number.isInteger(value) && value > 0 ? value : fallback;
35
+ }
36
+
37
+ function readyStateMatches(current, expected) {
38
+ const currentRank = READY_STATE_ORDER[current] ?? -1;
39
+ const expectedRank = READY_STATE_ORDER[expected] ?? -1;
40
+ return currentRank >= expectedRank;
41
+ }
42
+
43
+ function selectorMatches(result, state) {
44
+ if (state === "hidden") {
45
+ return !result?.found || result.node?.visible === false;
46
+ }
47
+
48
+ if (!result?.found) {
49
+ return false;
50
+ }
51
+
52
+ if (state === "present") {
53
+ return true;
54
+ }
55
+
56
+ return result.node?.visible === true;
57
+ }
58
+
59
+ function buildTimeoutMessage(options, lastPage, lastElement) {
60
+ const conditions = [];
61
+ if (options.selector) {
62
+ conditions.push(
63
+ `selector ${JSON.stringify(options.selector)} to become ${options.state}`,
64
+ );
65
+ }
66
+ if (options.url) {
67
+ conditions.push(`url to equal ${JSON.stringify(options.url)}`);
68
+ }
69
+ if (options.urlIncludes) {
70
+ conditions.push(`url to include ${JSON.stringify(options.urlIncludes)}`);
71
+ }
72
+ if (options.readyState) {
73
+ conditions.push(`readyState to reach ${options.readyState}`);
74
+ }
75
+
76
+ const observed = [];
77
+ if (lastPage?.url) {
78
+ observed.push(`last url=${JSON.stringify(lastPage.url)}`);
79
+ }
80
+ if (lastPage?.readyState) {
81
+ observed.push(`last readyState=${lastPage.readyState}`);
82
+ }
83
+ if (options.selector && lastElement) {
84
+ observed.push(
85
+ `last selector found=${Boolean(lastElement.found)} visible=${lastElement.node?.visible === true}`,
86
+ );
87
+ }
88
+
89
+ return `Timed out after ${options.timeoutMs}ms waiting for ${conditions.join(
90
+ ", ",
91
+ )}${observed.length > 0 ? `; ${observed.join("; ")}` : ""}`;
92
+ }
93
+
94
+ export function normalizeWaitForOptions(options = {}) {
95
+ const normalized = {
96
+ selector: normalizeOptionalString(options.selector),
97
+ state: normalizeSelectorState(options.state),
98
+ url: normalizeOptionalString(options.url),
99
+ urlIncludes: normalizeOptionalString(options.urlIncludes),
100
+ readyState: normalizeReadyState(options.readyState),
101
+ timeoutMs: normalizeInteger(options.timeoutMs, 10_000),
102
+ pollIntervalMs: normalizeInteger(options.pollIntervalMs, 100),
103
+ };
104
+
105
+ if (
106
+ !normalized.selector &&
107
+ !normalized.url &&
108
+ !normalized.urlIncludes &&
109
+ !normalized.readyState
110
+ ) {
111
+ throw new Error(
112
+ "wait_for requires at least one of selector, url, urlIncludes, or readyState",
113
+ );
114
+ }
115
+
116
+ if (!normalized.selector && options.state !== undefined) {
117
+ throw new Error("wait_for state requires selector");
118
+ }
119
+
120
+ return normalized;
121
+ }
122
+
123
+ export async function waitForPageCondition({
124
+ getPageState,
125
+ inspectElement,
126
+ options,
127
+ }) {
128
+ const normalized = normalizeWaitForOptions(options);
129
+ const startedAt = Date.now();
130
+ let attempts = 0;
131
+ let lastPage = null;
132
+ let lastElement = null;
133
+
134
+ while (true) {
135
+ attempts += 1;
136
+
137
+ if (normalized.url || normalized.urlIncludes || normalized.readyState) {
138
+ lastPage = await getPageState();
139
+ }
140
+
141
+ if (normalized.selector) {
142
+ lastElement = await inspectElement(normalized.selector);
143
+ if (lastElement?.error) {
144
+ throw new Error(lastElement.error);
145
+ }
146
+ }
147
+
148
+ const matchedSelector = normalized.selector
149
+ ? selectorMatches(lastElement, normalized.state)
150
+ : true;
151
+ const matchedUrl = normalized.url ? lastPage?.url === normalized.url : true;
152
+ const matchedUrlIncludes = normalized.urlIncludes
153
+ ? lastPage?.url?.includes(normalized.urlIncludes) === true
154
+ : true;
155
+ const matchedReadyState = normalized.readyState
156
+ ? readyStateMatches(lastPage?.readyState, normalized.readyState)
157
+ : true;
158
+
159
+ if (
160
+ matchedSelector &&
161
+ matchedUrl &&
162
+ matchedUrlIncludes &&
163
+ matchedReadyState
164
+ ) {
165
+ const browserFamily =
166
+ lastPage?.browserFamily ?? lastElement?.browserFamily ?? null;
167
+
168
+ return {
169
+ browserFamily,
170
+ matched: true,
171
+ waitedMs: Date.now() - startedAt,
172
+ attempts,
173
+ timeoutMs: normalized.timeoutMs,
174
+ pollIntervalMs: normalized.pollIntervalMs,
175
+ condition: {
176
+ selector: normalized.selector,
177
+ state: normalized.selector ? normalized.state : null,
178
+ url: normalized.url,
179
+ urlIncludes: normalized.urlIncludes,
180
+ readyState: normalized.readyState,
181
+ },
182
+ page: lastPage,
183
+ element: normalized.selector
184
+ ? {
185
+ selector: normalized.selector,
186
+ found: Boolean(lastElement?.found),
187
+ locator:
188
+ lastElement?.locator ?? lastElement?.node?.locator ?? null,
189
+ node: lastElement?.found ? lastElement.node : null,
190
+ }
191
+ : null,
192
+ };
193
+ }
194
+
195
+ if (Date.now() - startedAt >= normalized.timeoutMs) {
196
+ throw new Error(buildTimeoutMessage(normalized, lastPage, lastElement));
197
+ }
198
+
199
+ await sleep(normalized.pollIntervalMs);
200
+ }
201
+ }