@pyrokine/mcp-chrome 2.4.1 → 2.4.4

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 (105) hide show
  1. package/README.md +213 -158
  2. package/README_zh.md +245 -187
  3. package/dist/anti-detection/behavior.js +1 -1
  4. package/dist/anti-detection/behavior.js.map +1 -1
  5. package/dist/anti-detection/injection.d.ts.map +1 -1
  6. package/dist/anti-detection/injection.js +2 -1
  7. package/dist/anti-detection/injection.js.map +1 -1
  8. package/dist/cdp/client.d.ts +2 -2
  9. package/dist/cdp/client.d.ts.map +1 -1
  10. package/dist/cdp/client.js +7 -4
  11. package/dist/cdp/client.js.map +1 -1
  12. package/dist/core/browser-driver.d.ts +3 -2
  13. package/dist/core/browser-driver.d.ts.map +1 -1
  14. package/dist/core/browser-driver.js +1 -0
  15. package/dist/core/browser-driver.js.map +1 -1
  16. package/dist/core/errors.d.ts +9 -0
  17. package/dist/core/errors.d.ts.map +1 -1
  18. package/dist/core/errors.js +16 -1
  19. package/dist/core/errors.js.map +1 -1
  20. package/dist/core/os-mouse.d.ts +65 -0
  21. package/dist/core/os-mouse.d.ts.map +1 -0
  22. package/dist/core/os-mouse.js +334 -0
  23. package/dist/core/os-mouse.js.map +1 -0
  24. package/dist/core/session.d.ts +14 -4
  25. package/dist/core/session.d.ts.map +1 -1
  26. package/dist/core/session.js +159 -54
  27. package/dist/core/session.js.map +1 -1
  28. package/dist/core/types.d.ts +10 -0
  29. package/dist/core/types.d.ts.map +1 -1
  30. package/dist/core/types.js +2 -0
  31. package/dist/core/types.js.map +1 -1
  32. package/dist/core/unified-session.d.ts +24 -3
  33. package/dist/core/unified-session.d.ts.map +1 -1
  34. package/dist/core/unified-session.js +143 -25
  35. package/dist/core/unified-session.js.map +1 -1
  36. package/dist/extension/bridge.d.ts +16 -0
  37. package/dist/extension/bridge.d.ts.map +1 -1
  38. package/dist/extension/bridge.js +27 -0
  39. package/dist/extension/bridge.js.map +1 -1
  40. package/dist/extension/http-server.d.ts.map +1 -1
  41. package/dist/extension/http-server.js +6 -1
  42. package/dist/extension/http-server.js.map +1 -1
  43. package/dist/tools/browse.d.ts +1 -1
  44. package/dist/tools/browse.d.ts.map +1 -1
  45. package/dist/tools/browse.js +72 -26
  46. package/dist/tools/browse.js.map +1 -1
  47. package/dist/tools/challenge.d.ts +153 -0
  48. package/dist/tools/challenge.d.ts.map +1 -0
  49. package/dist/tools/challenge.js +573 -0
  50. package/dist/tools/challenge.js.map +1 -0
  51. package/dist/tools/cookies.d.ts.map +1 -1
  52. package/dist/tools/cookies.js +8 -4
  53. package/dist/tools/cookies.js.map +1 -1
  54. package/dist/tools/diagnostics.d.ts +2 -2
  55. package/dist/tools/diagnostics.d.ts.map +1 -1
  56. package/dist/tools/diagnostics.js +26 -8
  57. package/dist/tools/diagnostics.js.map +1 -1
  58. package/dist/tools/evaluate.d.ts.map +1 -1
  59. package/dist/tools/evaluate.js +61 -9
  60. package/dist/tools/evaluate.js.map +1 -1
  61. package/dist/tools/extract.d.ts.map +1 -1
  62. package/dist/tools/extract.js +110 -51
  63. package/dist/tools/extract.js.map +1 -1
  64. package/dist/tools/input.d.ts.map +1 -1
  65. package/dist/tools/input.js +148 -22
  66. package/dist/tools/input.js.map +1 -1
  67. package/dist/tools/logs.js +2 -2
  68. package/dist/tools/logs.js.map +1 -1
  69. package/dist/tools/manage.d.ts.map +1 -1
  70. package/dist/tools/manage.js +20 -7
  71. package/dist/tools/manage.js.map +1 -1
  72. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  73. package/dist/tools/network-sanitizer.js +1 -0
  74. package/dist/tools/network-sanitizer.js.map +1 -1
  75. package/dist/tools/png.js +5 -3
  76. package/dist/tools/png.js.map +1 -1
  77. package/dist/tools/post-condition.d.ts.map +1 -1
  78. package/dist/tools/post-condition.js +12 -3
  79. package/dist/tools/post-condition.js.map +1 -1
  80. package/dist/tools/target-diagnostics.d.ts +7 -0
  81. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  82. package/dist/tools/target-diagnostics.js +18 -1
  83. package/dist/tools/target-diagnostics.js.map +1 -1
  84. package/dist/tools/wait.d.ts.map +1 -1
  85. package/dist/tools/wait.js +41 -39
  86. package/dist/tools/wait.js.map +1 -1
  87. package/extension/dist/assets/{index.ts-GG6dPUPX.js → index.ts-Bqcu2qiN.js} +286 -9
  88. package/extension/dist/manifest.json +1 -1
  89. package/extension/dist/service-worker-loader.js +1 -1
  90. package/extension/dist/src/popup/popup.html +44 -44
  91. package/package.json +8 -7
  92. package/dist/extension/native-host-installer.d.ts +0 -21
  93. package/dist/extension/native-host-installer.d.ts.map +0 -1
  94. package/dist/extension/native-host-installer.js +0 -147
  95. package/dist/extension/native-host-installer.js.map +0 -1
  96. package/dist/extension/socket-server.d.ts +0 -32
  97. package/dist/extension/socket-server.d.ts.map +0 -1
  98. package/dist/extension/socket-server.js +0 -177
  99. package/dist/extension/socket-server.js.map +0 -1
  100. package/dist/extension/ws-server.d.ts +0 -40
  101. package/dist/extension/ws-server.d.ts.map +0 -1
  102. package/dist/extension/ws-server.js +0 -246
  103. package/dist/extension/ws-server.js.map +0 -1
  104. package/dist/native-host/index.js +0 -280
  105. package/dist/native-host/mcp-chrome-host +0 -2
@@ -112,7 +112,7 @@ async function assertManagedTab(tabId, context, operation) {
112
112
  mcpTabGroupId: context.mcpTabGroupId,
113
113
  windowId: tab.windowId,
114
114
  mcpWindowId: context.mcpWindowId
115
- })}, 请使用 browse(action="list") 选择 managed=true 的受控 tab, 或用 manage(action="newPage") 创建受控页面`);
115
+ })}, 请从 browse(action="list") 选择 managed=true 的 tab,或用 manage(action="newPage") 创建受控页面`);
116
116
  return tab;
117
117
  }
118
118
  var FRAME_PROBE_TIMEOUT_MS = 500;
@@ -4625,6 +4625,22 @@ var EvaluateSchema = object({
4625
4625
  frameId: frameIdOpt,
4626
4626
  code: string().min(1)
4627
4627
  });
4628
+ var ViewportMetricsSchema = object({
4629
+ tabId: tabIdOpt,
4630
+ frameId: frameIdOpt
4631
+ });
4632
+ var ChallengeInspectSchema = object({
4633
+ tabId: tabIdOpt,
4634
+ frameId: frameIdOpt,
4635
+ challengeSelectors: array(string()),
4636
+ deniedSelectors: array(string()),
4637
+ widgetSelectors: array(string()),
4638
+ verifyButtonSelectors: array(string()),
4639
+ frameSelectors: array(string()),
4640
+ titleNeedles: array(string()),
4641
+ textMarkers: array(string()),
4642
+ originResponsePendingTextMarkers: array(string())
4643
+ });
4628
4644
  var FindSchema = object({
4629
4645
  tabId: tabIdOpt,
4630
4646
  frameId: frameIdOpt,
@@ -4687,7 +4703,13 @@ var CookiesClearSchema = object({
4687
4703
  url: string().optional(),
4688
4704
  domain: string().optional(),
4689
4705
  name: string().optional()
4690
- }).partial().optional();
4706
+ }).partial().superRefine((value, ctx) => {
4707
+ if (!value.url && !value.domain) ctx.addIssue({
4708
+ code: "custom",
4709
+ path: ["url"],
4710
+ message: "cookies action=clear 必须带 url 或 domain 过滤参数"
4711
+ });
4712
+ }).optional();
4691
4713
  var DebuggerAttachSchema = object({ tabId: tabIdOpt }).partial().optional();
4692
4714
  var DebuggerDetachSchema = DebuggerAttachSchema;
4693
4715
  var DebuggerSendSchema = object({
@@ -4775,6 +4797,7 @@ var ConsoleEnableSchema = TabIdOnly;
4775
4797
  var ConsoleClearSchema = TabIdOnly;
4776
4798
  var NetworkEnableSchema = TabIdOnly;
4777
4799
  var NetworkClearSchema = TabIdOnly;
4800
+ var NetworkChallengeStateSchema = TabIdOnly;
4778
4801
  var ConsoleGetSchema = object({
4779
4802
  tabId: tabIdOpt,
4780
4803
  level: string().optional(),
@@ -5660,7 +5683,7 @@ async function simulateKeyboardType(text, delay) {
5660
5683
  };
5661
5684
  if (!(activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.isContentEditable)) return {
5662
5685
  success: false,
5663
- error: `Active element is not inputable: ${activeElement.tagName}`
5686
+ error: `Active element does not accept keyboard input: ${activeElement.tagName}`
5664
5687
  };
5665
5688
  const proto = Object.getPrototypeOf(activeElement);
5666
5689
  const valueSetter = Object.getOwnPropertyDescriptor(proto, "value") ?? Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value") ?? Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value");
@@ -6156,6 +6179,154 @@ function getComputedStyleFromElement(refId, prop) {
6156
6179
  }
6157
6180
  return cs.getPropertyValue(prop);
6158
6181
  }
6182
+ function inspectChallengePage(options) {
6183
+ const title = document.title || "";
6184
+ const url = location.href || "";
6185
+ const visibleBodyText = (document.body && document.body.innerText ? document.body.innerText : "").replace(/\s+/g, " ");
6186
+ const isVisible = (el) => {
6187
+ if (!el) return false;
6188
+ const style = window.getComputedStyle(el);
6189
+ if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return false;
6190
+ const rect = el.getBoundingClientRect();
6191
+ return rect.width > 0 && rect.height > 0;
6192
+ };
6193
+ const bringIntoView = (el) => {
6194
+ if (!el || typeof el.scrollIntoView !== "function") return;
6195
+ el.scrollIntoView({
6196
+ block: "center",
6197
+ inline: "nearest"
6198
+ });
6199
+ };
6200
+ const hits = (selectors) => selectors.filter((selector) => {
6201
+ try {
6202
+ return Array.from(document.querySelectorAll(selector)).some(isVisible);
6203
+ } catch {
6204
+ return false;
6205
+ }
6206
+ });
6207
+ const isCloudflareFrame = (el) => {
6208
+ if (!el) return false;
6209
+ if (el.tagName.toUpperCase() === "IFRAME") {
6210
+ const src = String(el.getAttribute("src") || el.src || "");
6211
+ return src.includes("challenges.cloudflare.com") || src.includes("turnstile");
6212
+ }
6213
+ return Boolean(el.closest(options.frameSelectors.join(",")));
6214
+ };
6215
+ const selectorHits = hits(options.challengeSelectors);
6216
+ const deniedHits = hits(options.deniedSelectors);
6217
+ const widgetHits = hits(options.widgetSelectors);
6218
+ const frameHits = hits(options.frameSelectors);
6219
+ const cloudflareFramePresent = Array.from(document.querySelectorAll("iframe")).some((el) => isCloudflareFrame(el));
6220
+ const normalizedTitle = title.trim().toLowerCase().replace(/…/g, "...");
6221
+ const titlePending = options.titleNeedles.some((needle) => normalizedTitle.includes(String(needle).toLowerCase()));
6222
+ const textHits = options.textMarkers.filter((marker) => visibleBodyText.toLowerCase().includes(String(marker).toLowerCase()));
6223
+ const originResponsePending = options.originResponsePendingTextMarkers.some((marker) => visibleBodyText.toLowerCase().includes(String(marker).toLowerCase()));
6224
+ const interstitialPending = selectorHits.length > 0 || titlePending || textHits.length > 0;
6225
+ const findVisibleTurnstileBox = () => {
6226
+ const input = document.querySelector("input[name=\"cf-turnstile-response\"]");
6227
+ if (!input) return null;
6228
+ const candidates = [];
6229
+ let node = input.parentElement;
6230
+ while (node && node !== document.documentElement) {
6231
+ if (isVisible(node)) {
6232
+ const rect = node.getBoundingClientRect();
6233
+ if (rect.width >= 120 && rect.height >= 40) candidates.push(node);
6234
+ }
6235
+ node = node.parentElement;
6236
+ }
6237
+ if (candidates.length === 0) return null;
6238
+ return candidates.find((el) => {
6239
+ const rect = el.getBoundingClientRect();
6240
+ return rect.width >= 250 && rect.width <= 340 && rect.height >= 50 && rect.height <= 85;
6241
+ }) || candidates[0];
6242
+ };
6243
+ const turnstileBox = findVisibleTurnstileBox();
6244
+ const hostVerify = Array.from(document.querySelectorAll(options.verifyButtonSelectors.join(","))).find(isVisible);
6245
+ const useIframeClick = cloudflareFramePresent || !hostVerify && interstitialPending && Boolean(document.querySelector("input[name=\"cf-turnstile-response\"]"));
6246
+ const turnstilePresent = widgetHits.length > 0 || useIframeClick || interstitialPending && frameHits.length > 0 || Boolean(turnstileBox);
6247
+ const pointFromRect = (rect, kind) => {
6248
+ if (!rect || rect.width < 8 || rect.height < 8) return null;
6249
+ const y = Math.round(rect.top + Math.min(rect.height, 65) / 2);
6250
+ if (kind === "verify") return {
6251
+ x: Math.round(rect.left + rect.width / 2),
6252
+ y
6253
+ };
6254
+ const widgetWidth = Math.min(rect.width, 300);
6255
+ return {
6256
+ x: Math.round(rect.left + Math.min(20, Math.max(14, widgetWidth / 15))),
6257
+ y
6258
+ };
6259
+ };
6260
+ let clickPoint = null;
6261
+ let clickTargetKind = null;
6262
+ let clickSource = null;
6263
+ const setClickTarget = (el, kind) => {
6264
+ if (!el) return;
6265
+ bringIntoView(el);
6266
+ const point = pointFromRect(el.getBoundingClientRect(), kind);
6267
+ if (!point) return;
6268
+ clickPoint = point;
6269
+ clickTargetKind = kind;
6270
+ clickSource = isCloudflareFrame(el) || useIframeClick ? "iframe" : "page";
6271
+ };
6272
+ if (hostVerify) setClickTarget(hostVerify, "verify");
6273
+ if (!clickPoint && turnstileBox) {
6274
+ const boxRect = turnstileBox.getBoundingClientRect();
6275
+ if (boxRect.width <= 340 && boxRect.height <= 85) setClickTarget(turnstileBox, "widget");
6276
+ }
6277
+ if (!clickPoint && turnstilePresent) {
6278
+ const frame = Array.from(document.querySelectorAll(options.frameSelectors.join(","))).find(isVisible);
6279
+ if (frame) setClickTarget(frame, "widget");
6280
+ }
6281
+ if (!clickPoint && turnstilePresent) {
6282
+ const widget = Array.from(document.querySelectorAll(options.widgetSelectors.join(","))).find(isVisible);
6283
+ if (widget) setClickTarget(widget, "widget");
6284
+ }
6285
+ if (!clickPoint && turnstilePresent) {
6286
+ const nodes = Array.from(document.querySelectorAll("div"));
6287
+ for (const node of nodes) {
6288
+ if (!isVisible(node)) continue;
6289
+ const rect = node.getBoundingClientRect();
6290
+ if (rect.width >= 280 && rect.width <= 320 && rect.height >= 50 && rect.height <= 80) {
6291
+ setClickTarget(node, "widget");
6292
+ break;
6293
+ }
6294
+ }
6295
+ }
6296
+ if (!clickPoint && turnstileBox) setClickTarget(turnstileBox, "widget");
6297
+ const viewport = {
6298
+ screenX: Number(window.screenX),
6299
+ screenY: Number(window.screenY),
6300
+ innerWidth: Number(window.innerWidth),
6301
+ innerHeight: Number(window.innerHeight),
6302
+ outerWidth: Number(window.outerWidth),
6303
+ outerHeight: Number(window.outerHeight),
6304
+ devicePixelRatio: Number(window.devicePixelRatio || 1)
6305
+ };
6306
+ const horizontal = Math.max(0, viewport.outerWidth - viewport.innerWidth);
6307
+ const vertical = Math.max(0, viewport.outerHeight - viewport.innerHeight);
6308
+ const chromeLeft = Math.round(horizontal / 2);
6309
+ const chromeTop = Math.max(0, vertical - horizontal);
6310
+ const resolvedClickPoint = clickPoint;
6311
+ const screenPoint = resolvedClickPoint === null ? null : {
6312
+ x: Math.round(viewport.screenX + chromeLeft + resolvedClickPoint.x),
6313
+ y: Math.round(viewport.screenY + chromeTop + resolvedClickPoint.y)
6314
+ };
6315
+ return {
6316
+ title,
6317
+ url,
6318
+ selectorHits,
6319
+ deniedHits,
6320
+ textHits,
6321
+ originResponsePending,
6322
+ turnstilePresent,
6323
+ clickPoint: resolvedClickPoint,
6324
+ clickTargetKind,
6325
+ clickSource,
6326
+ screenPoint,
6327
+ viewport
6328
+ };
6329
+ }
6159
6330
  //#endregion
6160
6331
  //#region src/background/content-handler.ts
6161
6332
  var EXPECTED_INJECTION_PATTERNS = [
@@ -6210,7 +6381,7 @@ var ContentHandler = class {
6210
6381
  expression: "document.visibilityState",
6211
6382
  returnByValue: true
6212
6383
  });
6213
- if (visibility?.value === "hidden") throw structuredOperationError$1("HIDDEN_TAB_SCREENSHOT", "screenshot 需要 tab 可见,当前 tab 处于 hidden 状态", "Extension 截图依赖可见 renderer,请显式使用 manage(action=\"activatePage\") 或 manage(action=\"focusWindow\"),也可在 CDP/headless 测试浏览器中截图", {
6384
+ if (visibility?.value === "hidden") throw structuredOperationError$1("HIDDEN_TAB_SCREENSHOT", "screenshot 需要 tab 可见,当前 tab 处于 hidden 状态", "Extension 截图依赖可见 renderer,请用 manage 的 activatePage 或 focusWindow 动作,也可在 CDP/headless 测试浏览器中截图", {
6214
6385
  tabId,
6215
6386
  visibilityState: visibility.value
6216
6387
  });
@@ -6337,6 +6508,58 @@ var ContentHandler = class {
6337
6508
  const tabId = await this.getManagedScriptableTabId(p.tabId, context, "evaluate");
6338
6509
  return this.injectScript(tabId, p.frameId, executeCode, [p.code]);
6339
6510
  }
6511
+ async getViewportMetrics(params, context) {
6512
+ const p = ViewportMetricsSchema.parse(params);
6513
+ const tabId = await this.getManagedScriptableTabId(p.tabId, context, "viewport_metrics");
6514
+ const results = await chrome.scripting.executeScript({
6515
+ target: {
6516
+ tabId,
6517
+ frameIds: [p.frameId ?? 0]
6518
+ },
6519
+ world: "ISOLATED",
6520
+ func: () => ({
6521
+ screenX: Number(window.screenX),
6522
+ screenY: Number(window.screenY),
6523
+ innerWidth: Number(window.innerWidth),
6524
+ innerHeight: Number(window.innerHeight),
6525
+ outerWidth: Number(window.outerWidth),
6526
+ outerHeight: Number(window.outerHeight),
6527
+ devicePixelRatio: Number(window.devicePixelRatio || 1)
6528
+ })
6529
+ });
6530
+ const injectionError = results[0]?.error;
6531
+ if (injectionError) throw wrapInjectionError(injectionError.message || String(injectionError));
6532
+ const metrics = results[0]?.result;
6533
+ if (!metrics) throw new Error("viewport_metrics 未返回视口");
6534
+ return metrics;
6535
+ }
6536
+ async inspectChallenge(params, context) {
6537
+ const p = ChallengeInspectSchema.parse(params);
6538
+ const tabId = await this.getManagedScriptableTabId(p.tabId, context, "challenge_inspect");
6539
+ const results = await chrome.scripting.executeScript({
6540
+ target: {
6541
+ tabId,
6542
+ frameIds: [p.frameId ?? 0]
6543
+ },
6544
+ world: "ISOLATED",
6545
+ func: inspectChallengePage,
6546
+ args: [{
6547
+ challengeSelectors: p.challengeSelectors,
6548
+ deniedSelectors: p.deniedSelectors,
6549
+ widgetSelectors: p.widgetSelectors,
6550
+ verifyButtonSelectors: p.verifyButtonSelectors,
6551
+ frameSelectors: p.frameSelectors,
6552
+ titleNeedles: p.titleNeedles,
6553
+ textMarkers: p.textMarkers,
6554
+ originResponsePendingTextMarkers: p.originResponsePendingTextMarkers
6555
+ }]
6556
+ });
6557
+ const injectionError = results[0]?.error;
6558
+ if (injectionError) throw wrapInjectionError(injectionError.message || String(injectionError));
6559
+ const snapshot = results[0]?.result;
6560
+ if (!snapshot) throw new Error("challenge_inspect 未返回页面状态");
6561
+ return snapshot;
6562
+ }
6340
6563
  async find(params, context) {
6341
6564
  const p = FindSchema.parse(params) ?? {};
6342
6565
  const tabId = await this.getManagedTabId(p.tabId, context, "find");
@@ -6513,7 +6736,7 @@ var CookieHandler = class {
6513
6736
  }
6514
6737
  async cookiesClear(params) {
6515
6738
  const p = CookiesClearSchema.parse(params) ?? {};
6516
- if (!p.url && !p.domain && !p.name) throw new ExpectedOperationError("cookies action=clear 必须带 name/domain/url 至少一个过滤参数(项目规范)");
6739
+ if (!p.url && !p.domain) throw new ExpectedOperationError("cookies action=clear 必须带 url 或 domain 过滤参数,name 只能在该范围内进一步过滤(避免跨站误删同名 cookie)");
6517
6740
  const filter = {};
6518
6741
  if (p.url) filter.url = p.url;
6519
6742
  if (p.domain) filter.domain = p.domain;
@@ -7167,6 +7390,8 @@ var LogEventHandler = class {
7167
7390
  } catch (e) {
7168
7391
  console.warn("[logs] console fallback (executeScript) failed:", e);
7169
7392
  }
7393
+ this.logManager.setConsole(tabId, messages);
7394
+ messages = this.logManager.getConsole(tabId);
7170
7395
  if (p.level) {
7171
7396
  const target = p.level;
7172
7397
  messages = messages.filter((m) => m.level === target || target === "warning" && m.level === "warn" || target === "warn" && m.level === "warning");
@@ -7257,6 +7482,11 @@ var LogEventHandler = class {
7257
7482
  this.logManager.setNetwork(tabId, []);
7258
7483
  return { success: true };
7259
7484
  }
7485
+ async networkChallengeState(params, context) {
7486
+ const p = NetworkChallengeStateSchema.parse(params) ?? {};
7487
+ const tabId = await this.getManagedTabId(p.tabId, context, "network_challenge_state");
7488
+ return { challengeRequired: this.logManager.isChallengeRequired(tabId) };
7489
+ }
7260
7490
  async getManagedTabId(tabId, context, operation) {
7261
7491
  const resolvedTabId = await getTargetTabId(tabId);
7262
7492
  await assertManagedTab(resolvedTabId, context, operation);
@@ -7312,9 +7542,16 @@ var LogEventHandler = class {
7312
7542
  var PENDING_TTL_MS = 6e4;
7313
7543
  var PENDING_MAX_PER_TAB = 500;
7314
7544
  var PENDING_SWEEP_INTERVAL_MS = 3e4;
7545
+ function isCloudflareChallenge(headers) {
7546
+ if (!headers) return false;
7547
+ return Object.entries(headers).some(([name, value]) => name.toLowerCase() === "cf-mitigated" && String(value).toLowerCase() === "challenge");
7548
+ }
7315
7549
  var LogManager = class {
7316
7550
  consoleMessages = /* @__PURE__ */ new Map();
7317
7551
  networkRequests = /* @__PURE__ */ new Map();
7552
+ consoleSequences = /* @__PURE__ */ new Map();
7553
+ networkSequences = /* @__PURE__ */ new Map();
7554
+ challengeRequired = /* @__PURE__ */ new Map();
7318
7555
  pendingRequests = /* @__PURE__ */ new Map();
7319
7556
  sweepTimer = null;
7320
7557
  constructor() {
@@ -7330,6 +7567,7 @@ var LogManager = class {
7330
7567
  }
7331
7568
  /** 替换 console 消息列表(清理或覆盖场景) */
7332
7569
  setConsole(tabId, messages) {
7570
+ this.assignConsoleSequences(tabId, messages);
7333
7571
  this.consoleMessages.set(tabId, messages);
7334
7572
  }
7335
7573
  /** 是否已为 tab 初始化 network 缓冲 */
@@ -7340,8 +7578,12 @@ var LogManager = class {
7340
7578
  getNetwork(tabId) {
7341
7579
  return this.networkRequests.get(tabId) ?? [];
7342
7580
  }
7581
+ isChallengeRequired(tabId) {
7582
+ return this.challengeRequired.get(tabId) === true;
7583
+ }
7343
7584
  /** 替换 network 请求列表 */
7344
7585
  setNetwork(tabId, requests) {
7586
+ this.assignNetworkSequences(tabId, requests);
7345
7587
  this.networkRequests.set(tabId, requests);
7346
7588
  }
7347
7589
  /** 取 pending 请求 Map(navigation-handler 用于过滤进行中的请求) */
@@ -7377,6 +7619,7 @@ var LogManager = class {
7377
7619
  lineNumber: p.exceptionDetails.lineNumber
7378
7620
  };
7379
7621
  const messages = this.consoleMessages.get(tabId) || [];
7622
+ this.assignConsoleSequences(tabId, [message]);
7380
7623
  messages.push(message);
7381
7624
  if (messages.length > 1100) messages.splice(0, messages.length - 1e3);
7382
7625
  this.consoleMessages.set(tabId, messages);
@@ -7412,12 +7655,16 @@ var LogManager = class {
7412
7655
  const pending = tabPending?.get(p.requestId);
7413
7656
  if (pending) {
7414
7657
  const { _monotonic, _addedAt: _, ...requestData } = pending;
7658
+ const challenge = isCloudflareChallenge(p.response.headers);
7659
+ if (requestData.type.toLowerCase() === "document") this.challengeRequired.set(tabId, challenge);
7415
7660
  const requests = this.networkRequests.get(tabId) || [];
7416
7661
  requests.push({
7417
7662
  ...requestData,
7418
7663
  status: p.response.status,
7664
+ challenge,
7419
7665
  duration: Math.round((p.timestamp - _monotonic) * 1e3)
7420
7666
  });
7667
+ this.assignNetworkSequences(tabId, requests.slice(-1));
7421
7668
  if (requests.length > 1100) requests.splice(0, requests.length - 1e3);
7422
7669
  this.networkRequests.set(tabId, requests);
7423
7670
  tabPending.delete(p.requestId);
@@ -7435,6 +7682,7 @@ var LogManager = class {
7435
7682
  errorText: p.errorText,
7436
7683
  duration: Math.round((p.timestamp - _monotonic) * 1e3)
7437
7684
  });
7685
+ this.assignNetworkSequences(tabId, requests.slice(-1));
7438
7686
  if (requests.length > 1100) requests.splice(0, requests.length - 1e3);
7439
7687
  this.networkRequests.set(tabId, requests);
7440
7688
  }
@@ -7444,8 +7692,23 @@ var LogManager = class {
7444
7692
  cleanupTab(tabId) {
7445
7693
  this.consoleMessages.delete(tabId);
7446
7694
  this.networkRequests.delete(tabId);
7695
+ this.consoleSequences.delete(tabId);
7696
+ this.networkSequences.delete(tabId);
7697
+ this.challengeRequired.delete(tabId);
7447
7698
  this.pendingRequests.delete(tabId);
7448
7699
  }
7700
+ assignConsoleSequences(tabId, messages) {
7701
+ let sequence = this.consoleSequences.get(tabId) ?? 0;
7702
+ for (const message of messages) if (message.sequence === void 0) message.sequence = ++sequence;
7703
+ else sequence = Math.max(sequence, message.sequence);
7704
+ this.consoleSequences.set(tabId, sequence);
7705
+ }
7706
+ assignNetworkSequences(tabId, requests) {
7707
+ let sequence = this.networkSequences.get(tabId) ?? 0;
7708
+ for (const request of requests) if (request.sequence === void 0) request.sequence = ++sequence;
7709
+ else sequence = Math.max(sequence, request.sequence);
7710
+ this.networkSequences.set(tabId, sequence);
7711
+ }
7449
7712
  startSweep() {
7450
7713
  if (this.sweepTimer) return;
7451
7714
  this.sweepTimer = setInterval(() => this.sweepPending(), PENDING_SWEEP_INTERVAL_MS);
@@ -8058,7 +8321,7 @@ var TabHandler = class {
8058
8321
  const before = await assertManagedWindow(p.windowId, context, "window_focus");
8059
8322
  await chrome.windows.update(p.windowId, { focused: true });
8060
8323
  const after = await waitForWindowFocus(p.windowId, context);
8061
- if (!after.focused) throw structuredOperationError("WINDOW_FOCUS_NOT_OBSERVED", "focusWindow 已请求聚焦窗口,但 Chrome 未观测到目标窗口获得焦点", "请确认目标窗口属于 managed 测试窗口,并检查当前桌面环境是否允许浏览器扩展主动聚焦窗口;需要可见 tab 时可改用 manage(action=\"activatePage\") 激活目标测试 tab", {
8324
+ if (!after.focused) throw structuredOperationError("WINDOW_FOCUS_NOT_OBSERVED", "focusWindow 已请求聚焦窗口,但 Chrome 未观测到目标窗口获得焦点", "请确认目标是 managed 测试窗口,并检查桌面环境是否允许扩展聚焦窗口;需要可见 tab 时可用 manage(action=\"activatePage\") 激活目标测试 tab", {
8062
8325
  windowId: p.windowId,
8063
8326
  beforeFocused: before.focused,
8064
8327
  afterFocused: after.focused,
@@ -8106,7 +8369,7 @@ var TabHandler = class {
8106
8369
  setMcpWindowId(window.id);
8107
8370
  const tabId = window.tabs?.[0]?.id;
8108
8371
  if (tabId !== void 0) await markManagedTab(tabId);
8109
- const after = await getWindowInfo(window.id, context);
8372
+ const after = p.focused ? await waitForWindowFocus(window.id, context) : await getWindowInfo(window.id, context);
8110
8373
  return {
8111
8374
  success: true,
8112
8375
  windowId: window.id,
@@ -8166,6 +8429,11 @@ var TabHandler = class {
8166
8429
  };
8167
8430
  //#endregion
8168
8431
  //#region src/background/actions.ts
8432
+ /**
8433
+ * Action 处理器
8434
+ *
8435
+ * 处理来自 MCP Server 的所有操作请求
8436
+ */
8169
8437
  var ActionHandler = class {
8170
8438
  actions = /* @__PURE__ */ new Map();
8171
8439
  logManager = new LogManager();
@@ -8185,7 +8453,10 @@ var ActionHandler = class {
8185
8453
  }
8186
8454
  async execute(action, params, context) {
8187
8455
  const handler = this.actions.get(action);
8188
- if (!handler) throw new Error(`Unknown action: ${action}`);
8456
+ if (!handler) throw new ExpectedOperationError(JSON.stringify({ error: {
8457
+ code: "UNKNOWN_ACTION",
8458
+ message: `Unknown action: ${action}`
8459
+ } }));
8189
8460
  return handler(params, context);
8190
8461
  }
8191
8462
  /**
@@ -8227,6 +8498,8 @@ var ActionHandler = class {
8227
8498
  this.actions.set("type", this.contentHandler.type.bind(this.contentHandler));
8228
8499
  this.actions.set("scroll", this.contentHandler.scroll.bind(this.contentHandler));
8229
8500
  this.actions.set("evaluate", this.contentHandler.evaluate.bind(this.contentHandler));
8501
+ this.actions.set("viewport_metrics", this.contentHandler.getViewportMetrics.bind(this.contentHandler));
8502
+ this.actions.set("challenge_inspect", this.contentHandler.inspectChallenge.bind(this.contentHandler));
8230
8503
  this.actions.set("find", this.contentHandler.find.bind(this.contentHandler));
8231
8504
  this.actions.set("get_text", this.contentHandler.getText.bind(this.contentHandler));
8232
8505
  this.actions.set("get_html", this.contentHandler.getHtml.bind(this.contentHandler));
@@ -8252,6 +8525,7 @@ var ActionHandler = class {
8252
8525
  this.actions.set("network_enable", this.logEventHandler.networkEnable.bind(this.logEventHandler));
8253
8526
  this.actions.set("network_get", this.logEventHandler.networkGet.bind(this.logEventHandler));
8254
8527
  this.actions.set("network_clear", this.logEventHandler.networkClear.bind(this.logEventHandler));
8528
+ this.actions.set("network_challenge_state", this.logEventHandler.networkChallengeState.bind(this.logEventHandler));
8255
8529
  this.actions.set("stealth_click", this.stealthHandler.stealthClick.bind(this.stealthHandler));
8256
8530
  this.actions.set("stealth_type", this.stealthHandler.stealthType.bind(this.stealthHandler));
8257
8531
  this.actions.set("stealth_key", this.stealthHandler.stealthKey.bind(this.stealthHandler));
@@ -8542,7 +8816,10 @@ var HttpClient = class {
8542
8816
  const healthyPorts = results.filter(({ result }) => result.healthy).map(({ port }) => port);
8543
8817
  const selectedFailures = results.filter(({ result }) => result.failureKind);
8544
8818
  const failureSummary = selectedFailures.slice(0, 10).map(({ port, result }) => `${port} (${result.failureKind}: ${result.reason})`).join(", ");
8545
- if (failureSummary && failureSummary !== this.lastServerFailureSummary) console.warn(`[HTTP] ${selectedFailures.length} MCP Server candidate(s) rejected after health identification: ${failureSummary}${selectedFailures.length > 10 ? ", ..." : ""}`);
8819
+ if (failureSummary && failureSummary !== this.lastServerFailureSummary) {
8820
+ const omittedSuffix = selectedFailures.length > 10 ? ", ..." : "";
8821
+ console.warn(`[HTTP] ${selectedFailures.length} MCP Server candidate(s) rejected after health identification: ` + failureSummary + omittedSuffix);
8822
+ }
8546
8823
  this.lastServerFailureSummary = failureSummary;
8547
8824
  if (healthyPorts.length > 0) console.log(`[HTTP] Found ${healthyPorts.length} MCP Server(s) at ports: ${healthyPorts.sort((a, b) => a - b).join(", ")}`);
8548
8825
  else console.log("[HTTP] No MCP Server found in port range");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "MCP Chrome",
4
- "version": "2.4.1",
4
+ "version": "2.4.4",
5
5
  "description": "Browser automation for Claude Code via MCP protocol",
6
6
  "permissions": [
7
7
  "alarms",
@@ -1 +1 @@
1
- import './assets/index.ts-GG6dPUPX.js';
1
+ import './assets/index.ts-Bqcu2qiN.js';
@@ -1,50 +1,50 @@
1
- <!DOCTYPE html>
2
- <html lang='zh-CN'>
3
- <head>
4
- <meta charset='UTF-8'>
5
- <meta content='width=device-width, initial-scale=1.0' name='viewport'>
6
- <title>MCP Chrome</title>
7
- <script type="module" crossorigin src="/assets/popup.html-B81xccfq.js"></script>
8
- <link rel="stylesheet" crossorigin href="/assets/popup-BwuBB9Cz.css">
9
- </head>
10
- <body>
11
- <div class='container'>
12
- <h1>MCP Chrome</h1>
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta content="width=device-width, initial-scale=1.0" name="viewport" />
6
+ <title>MCP Chrome</title>
7
+ <script type="module" crossorigin src="/assets/popup.html-B81xccfq.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/popup-BwuBB9Cz.css">
9
+ </head>
10
+ <body>
11
+ <div class="container">
12
+ <h1>MCP Chrome</h1>
13
13
 
14
- <div class='status-section'>
15
- <div class='status-indicator' id='statusIndicator'>
16
- <span class='status-dot'></span>
17
- <span class='status-text' id='statusText'>检查中...</span>
18
- </div>
19
- </div>
14
+ <div class="status-section">
15
+ <div class="status-indicator" id="statusIndicator">
16
+ <span class="status-dot"></span>
17
+ <span class="status-text" id="statusText">检查中...</span>
18
+ </div>
19
+ </div>
20
20
 
21
- <div class='button-section'>
22
- <button class='btn btn-primary' id='connectBtn'>连接</button>
23
- <button class='btn btn-secondary' disabled id='disconnectBtn'>断开</button>
24
- </div>
21
+ <div class="button-section">
22
+ <button class="btn btn-primary" id="connectBtn">连接</button>
23
+ <button class="btn btn-secondary" disabled id="disconnectBtn">断开</button>
24
+ </div>
25
25
 
26
- <div class='auth-section'>
27
- <label class='auth-label' for='pairingTokenInput'>Pairing token</label>
28
- <input autocomplete='off' class='auth-input' id='pairingTokenInput'
29
- placeholder='可选,必须与 MCP_CHROME_PAIRING_TOKEN 一致'
30
- type='password'>
31
- <button class='btn btn-secondary' id='saveTokenBtn'>保存 token</button>
32
- <label class='auth-checkbox'>
33
- <input id='allowInsecureNoTokenInput' type='checkbox'>
34
- 允许无 token 本地连接
35
- </label>
36
- <p class='auth-help' id='authHelp'>默认自动连接本地 MCP Server,可用 pairing token 加固</p>
37
- </div>
26
+ <div class="auth-section">
27
+ <label class="auth-label" for="pairingTokenInput">Pairing token</label>
28
+ <input
29
+ autocomplete="off"
30
+ class="auth-input"
31
+ id="pairingTokenInput"
32
+ placeholder="可选,必须与 MCP_CHROME_PAIRING_TOKEN 一致"
33
+ type="password"
34
+ />
35
+ <button class="btn btn-secondary" id="saveTokenBtn">保存 token</button>
36
+ <label class="auth-checkbox">
37
+ <input id="allowInsecureNoTokenInput" type="checkbox" />
38
+ 允许无 token 本地连接
39
+ </label>
40
+ <p class="auth-help" id="authHelp">默认自动连接本地 MCP Server,可用 pairing token 加固</p>
41
+ </div>
38
42
 
39
- <div class='info-section'>
40
- <p class='info-text'>
41
- 通过 WebSocket 与 MCP Server 通信
42
- </p>
43
- <p class='info-text'>
44
- 服务端口范围:19222-19299
45
- </p>
46
- </div>
47
- </div>
43
+ <div class="info-section">
44
+ <p class="info-text">通过 WebSocket 与 MCP Server 通信</p>
45
+ <p class="info-text">服务端口范围:19222-19299</p>
46
+ </div>
47
+ </div>
48
48
 
49
- </body>
49
+ </body>
50
50
  </html>
package/package.json CHANGED
@@ -1,20 +1,21 @@
1
1
  {
2
2
  "name": "@pyrokine/mcp-chrome",
3
- "version": "2.4.1",
3
+ "version": "2.4.4",
4
4
  "description": "Chrome browser automation MCP Server using Chrome DevTools Protocol",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
7
7
  "scripts": {
8
- "build": "node node_modules/typescript7/bin/tsc",
8
+ "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
9
+ "build": "npm run clean && node node_modules/typescript7/bin/tsc",
9
10
  "build:extension": "npm --prefix extension ci --include=optional && npm --prefix extension run build",
10
11
  "start": "node dist/index.js",
11
12
  "dev": "node node_modules/typescript7/bin/tsc -w",
12
13
  "prepare": "npm run build",
13
14
  "prepack": "npm run build && npm run build:extension",
14
- "lint": "eslint \"src/**/*.ts\" \"extension/src/**/*.ts\"",
15
- "lint:fix": "eslint \"src/**/*.ts\" \"extension/src/**/*.ts\" --fix",
16
- "format": "prettier --write src/",
17
- "format:check": "prettier --check src/",
15
+ "lint": "eslint \"src/**/*.ts\" \"extension/src/**/*.ts\" \"test/**/*.js\"",
16
+ "lint:fix": "eslint \"src/**/*.ts\" \"extension/src/**/*.ts\" \"test/**/*.js\" --fix",
17
+ "format": "prettier -w --prose-wrap=always src extension/src test README.md README_zh.md TESTING.md",
18
+ "format:check": "prettier -c --prose-wrap=always src extension/src test README.md README_zh.md TESTING.md",
18
19
  "test": "npm run build && node --test test/ch-regressions.test.js"
19
20
  },
20
21
  "keywords": [
@@ -28,7 +29,7 @@
28
29
  "author": "Pyrokine",
29
30
  "license": "MIT",
30
31
  "dependencies": {
31
- "@modelcontextprotocol/sdk": "^1.29.0",
32
+ "@modelcontextprotocol/sdk": "^1.30.0",
32
33
  "ws": "^8.21.1",
33
34
  "zod": "^4.4.3"
34
35
  },
@@ -1,21 +0,0 @@
1
- /**
2
- * Native Host 自动安装器
3
- *
4
- * 在 MCP Server 启动时自动检测并安装 Native Host
5
- */
6
- /**
7
- * 安装 Native Host
8
- */
9
- export declare function installNativeHost(extensionId?: string): {
10
- success: boolean;
11
- message: string;
12
- };
13
- /**
14
- * 检查 Native Host 是否已安装
15
- */
16
- export declare function isNativeHostInstalled(): boolean;
17
- /**
18
- * 获取 Native Host 名称(供 Extension 使用)
19
- */
20
- export declare function getNativeHostName(): string;
21
- //# sourceMappingURL=native-host-installer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"native-host-installer.d.ts","sourceRoot":"","sources":["../../src/extension/native-host-installer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AA2FH;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAC,CAyD3F;AAED;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,OAAO,CAQ/C;AAED;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C"}