browser-ref-mcp 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/README.md +174 -2
- package/README.zh-CN.md +157 -0
- package/dist/actions.js +381 -0
- package/dist/browserManager.js +410 -0
- package/dist/config.js +125 -0
- package/dist/errors.js +52 -0
- package/dist/index.js +77 -0
- package/dist/session.js +176 -0
- package/dist/snapshot.js +707 -0
- package/dist/tools.js +498 -0
- package/dist/util.js +113 -0
- package/package.json +53 -4
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// 浏览器生命周期管理:启动 / 健康检查 / 崩溃懒重启 / 会话恢复 / 弹窗与对话框 / 下载
|
|
2
|
+
import { chromium, } from "playwright-core";
|
|
3
|
+
import { mkdir } from "node:fs/promises";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { SessionTracker } from "./session.js";
|
|
7
|
+
import { log, withTimeout, uid } from "./util.js";
|
|
8
|
+
import { ToolError } from "./errors.js";
|
|
9
|
+
const MAX_RING = 20;
|
|
10
|
+
export class BrowserManager {
|
|
11
|
+
cfg;
|
|
12
|
+
session;
|
|
13
|
+
state = "stopped";
|
|
14
|
+
context = null;
|
|
15
|
+
browser = null;
|
|
16
|
+
launching = null;
|
|
17
|
+
crashedAt = 0;
|
|
18
|
+
lastError = null;
|
|
19
|
+
restartCount = 0;
|
|
20
|
+
launchedAt = null;
|
|
21
|
+
/** 最近弹出的新标签(context.on("page") 记录,供点击结果提示) */
|
|
22
|
+
recentPopups = [];
|
|
23
|
+
recentDialogs = [];
|
|
24
|
+
recentDownloads = [];
|
|
25
|
+
/** 供 resolveTarget 按登记 id 找页面 */
|
|
26
|
+
get pages() {
|
|
27
|
+
return this.session;
|
|
28
|
+
}
|
|
29
|
+
constructor(cfg) {
|
|
30
|
+
this.cfg = cfg;
|
|
31
|
+
this.session = new SessionTracker(cfg.stateDir);
|
|
32
|
+
}
|
|
33
|
+
// ---------------- 健康检查与懒重启 ----------------
|
|
34
|
+
/**
|
|
35
|
+
* 每次工具调用前调用。已就绪直接返回;崩溃/未启动则启动并恢复会话。
|
|
36
|
+
* 返回 notes 里包含需要呈现给 agent 的状态变化(如“浏览器已自动重启”)。
|
|
37
|
+
*/
|
|
38
|
+
async ensureReady(force = false) {
|
|
39
|
+
const notes = [];
|
|
40
|
+
if (force) {
|
|
41
|
+
notes.push("已强制重启浏览器,所有旧 ref 失效,请重新 browser_snapshot。");
|
|
42
|
+
await this.killOwnBrowser();
|
|
43
|
+
this.state = "crashed";
|
|
44
|
+
}
|
|
45
|
+
const healthy = this.state === "ready" &&
|
|
46
|
+
!!this.context &&
|
|
47
|
+
!!this.browser &&
|
|
48
|
+
this.browser.isConnected();
|
|
49
|
+
if (healthy)
|
|
50
|
+
return notes;
|
|
51
|
+
if (this.state !== "ready" && this.crashedAt > 0) {
|
|
52
|
+
notes.push("⚠️ 检测到浏览器已断开/崩溃,正在自动重启并恢复会话…");
|
|
53
|
+
}
|
|
54
|
+
if (this.launching) {
|
|
55
|
+
await this.launching;
|
|
56
|
+
return notes;
|
|
57
|
+
}
|
|
58
|
+
this.launching = this.doLaunch(notes).finally(() => {
|
|
59
|
+
this.launching = null;
|
|
60
|
+
});
|
|
61
|
+
await this.launching;
|
|
62
|
+
return notes;
|
|
63
|
+
}
|
|
64
|
+
async doLaunch(notes) {
|
|
65
|
+
this.state = "starting";
|
|
66
|
+
try {
|
|
67
|
+
await mkdir(this.cfg.downloadDir, { recursive: true });
|
|
68
|
+
if (this.cfg.mode === "connect") {
|
|
69
|
+
await this.connect(notes);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
await this.launchOwn(notes);
|
|
73
|
+
}
|
|
74
|
+
this.state = "ready";
|
|
75
|
+
this.launchedAt = Date.now();
|
|
76
|
+
this.lastError = null;
|
|
77
|
+
this.restartCount++;
|
|
78
|
+
void log("info", `browser ready (mode=${this.cfg.mode}, restart=#${this.restartCount})`);
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
this.state = "crashed";
|
|
82
|
+
this.crashedAt = Date.now();
|
|
83
|
+
this.lastError = e instanceof Error ? e.message : String(e);
|
|
84
|
+
void log("error", "launch failed", this.lastError);
|
|
85
|
+
throw e;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// ---------------- 专用浏览器(launch 模式) ----------------
|
|
89
|
+
launchArgs() {
|
|
90
|
+
const args = [
|
|
91
|
+
"--no-first-run",
|
|
92
|
+
"--no-default-browser-check",
|
|
93
|
+
// 窗口失焦时不禁定时器/渲染 —— agent 使用时窗口经常不在前台
|
|
94
|
+
"--disable-background-timer-throttling",
|
|
95
|
+
"--disable-backgrounding-occluded-windows",
|
|
96
|
+
"--disable-renderer-backgrounding",
|
|
97
|
+
"--disable-blink-features=AutomationControlled",
|
|
98
|
+
...this.cfg.extraArgs,
|
|
99
|
+
];
|
|
100
|
+
if (!this.cfg.headless && this.cfg.viewport === null)
|
|
101
|
+
args.push("--start-maximized");
|
|
102
|
+
return args;
|
|
103
|
+
}
|
|
104
|
+
launchOptionsFor(channel, executablePath) {
|
|
105
|
+
const headless = this.cfg.headless;
|
|
106
|
+
return {
|
|
107
|
+
channel: channel,
|
|
108
|
+
executablePath,
|
|
109
|
+
headless,
|
|
110
|
+
viewport: headless ? this.cfg.viewport ?? { width: 1440, height: 900 } : this.cfg.viewport,
|
|
111
|
+
args: this.launchArgs(),
|
|
112
|
+
ignoreDefaultArgs: ["--enable-automation"],
|
|
113
|
+
acceptDownloads: true,
|
|
114
|
+
timeout: 30000,
|
|
115
|
+
locale: this.cfg.locale,
|
|
116
|
+
env: undefined,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
async launchOwn(notes) {
|
|
120
|
+
const candidates = [];
|
|
121
|
+
if (this.cfg.executablePath) {
|
|
122
|
+
candidates.push({ executablePath: this.cfg.executablePath });
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
for (const c of this.cfg.channels)
|
|
126
|
+
candidates.push({ channel: c });
|
|
127
|
+
}
|
|
128
|
+
let lastErr = null;
|
|
129
|
+
for (const cand of candidates) {
|
|
130
|
+
// 第一次尝试失败且疑似 profile 被占(残留进程)时,定向清理后重试一次
|
|
131
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
132
|
+
try {
|
|
133
|
+
void log("info", `launching via ${cand.channel ?? cand.executablePath} (attempt ${attempt + 1})`);
|
|
134
|
+
const context = await withTimeout(chromium.launchPersistentContext(this.cfg.profileDir, this.launchOptionsFor(cand.channel, cand.executablePath)), 45000, "启动浏览器");
|
|
135
|
+
this.context = context;
|
|
136
|
+
this.browser = context.browser();
|
|
137
|
+
const { restoredCount } = await this.attachContext(context, { restoreSession: true });
|
|
138
|
+
if (restoredCount > 0)
|
|
139
|
+
notes.push(`已恢复 ${restoredCount} 个标签页。`);
|
|
140
|
+
notes.push(`已启动专用浏览器(${cand.channel ?? "自定义路径"}, profile: ${this.cfg.profileDir}, ${this.cfg.headless ? "无头" : "有头"})。`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
catch (e) {
|
|
144
|
+
lastErr = e;
|
|
145
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
146
|
+
void log("warn", "launch attempt failed", msg);
|
|
147
|
+
const looksLocked = /ProcessSingleton|SingletonLock|already running|Failed to create|user data directory/i.test(msg);
|
|
148
|
+
if (attempt === 0 && looksLocked) {
|
|
149
|
+
notes.push("profile 疑似被残留进程占用,正在清理…");
|
|
150
|
+
await this.killOrphanByProfile();
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
throw new ToolError("launch_failed", `无法启动浏览器:${lastErr instanceof Error ? lastErr.message : String(lastErr)}`, "已依次尝试渠道:" + (this.cfg.executablePath ? this.cfg.executablePath : this.cfg.channels.join(" → ")) + "。可检查 config.json 的 channels/executablePath,或确认 Chrome/Edge 已安装。");
|
|
159
|
+
}
|
|
160
|
+
/** 按 profile 路径定向清理残留 Chrome 进程(Windows: PowerShell Get-CimInstance) */
|
|
161
|
+
/** 由启动时记录的本浏览器进程 pid(供 get_info 展示与定向清理;best-effort) */
|
|
162
|
+
browserPids = [];
|
|
163
|
+
async recordBrowserPids() {
|
|
164
|
+
if (process.platform !== "win32")
|
|
165
|
+
return;
|
|
166
|
+
const profile = path.resolve(this.cfg.profileDir).toLowerCase();
|
|
167
|
+
const ps = `
|
|
168
|
+
Get-CimInstance Win32_Process -Filter "Name='chrome.exe' or Name='msedge.exe'" |
|
|
169
|
+
Where-Object { $_.CommandLine -and $_.CommandLine.ToLower().Contains('${profile.replace(/'/g, "''")}') } |
|
|
170
|
+
ForEach-Object { $_.ProcessId }
|
|
171
|
+
`.trim();
|
|
172
|
+
await new Promise((resolve) => {
|
|
173
|
+
execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ps], { timeout: 15000 }, (err, stdout) => {
|
|
174
|
+
if (!err && stdout) {
|
|
175
|
+
this.browserPids = stdout.split(/\s+/).filter((s) => /^\d+$/.test(s));
|
|
176
|
+
}
|
|
177
|
+
resolve();
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
void log("info", "browser pids recorded", this.browserPids);
|
|
181
|
+
}
|
|
182
|
+
async killOrphanByProfile() {
|
|
183
|
+
if (process.platform !== "win32")
|
|
184
|
+
return;
|
|
185
|
+
const profile = path.resolve(this.cfg.profileDir).toLowerCase();
|
|
186
|
+
const ps = `
|
|
187
|
+
Get-CimInstance Win32_Process -Filter "Name='chrome.exe' or Name='msedge.exe'" |
|
|
188
|
+
Where-Object { $_.CommandLine -and $_.CommandLine.ToLower().Contains('${profile.replace(/'/g, "''")}') } |
|
|
189
|
+
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
|
|
190
|
+
`.trim();
|
|
191
|
+
await new Promise((resolve) => {
|
|
192
|
+
execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ps], { timeout: 15000 }, () => resolve());
|
|
193
|
+
});
|
|
194
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
195
|
+
}
|
|
196
|
+
// ---------------- 外连浏览器(connect 模式) ----------------
|
|
197
|
+
async connect(notes) {
|
|
198
|
+
const url = this.cfg.cdpUrl;
|
|
199
|
+
let browser;
|
|
200
|
+
try {
|
|
201
|
+
browser = await withTimeout(chromium.connectOverCDP(url, { timeout: 10000 }), 15000, "连接 CDP");
|
|
202
|
+
}
|
|
203
|
+
catch (e) {
|
|
204
|
+
throw new ToolError("connect_failed", `无法连接浏览器 ${url}:${e instanceof Error ? e.message : String(e)}`, "请确认目标浏览器已带调试端口启动,例如:chrome.exe --remote-debugging-port=9222");
|
|
205
|
+
}
|
|
206
|
+
this.browser = browser;
|
|
207
|
+
const ctx = browser.contexts()[0] ?? (await browser.newContext());
|
|
208
|
+
this.context = ctx;
|
|
209
|
+
await this.attachContext(ctx, { restoreSession: false, adoptExisting: true });
|
|
210
|
+
notes.push(`已连接到现有浏览器(${url}),退出时不会关闭它。`);
|
|
211
|
+
}
|
|
212
|
+
// ---------------- 事件挂载 ----------------
|
|
213
|
+
async attachContext(ctx, opts) {
|
|
214
|
+
// 事件注册必须先于一切业务操作(含会话恢复),否则会漏掉期间发生的页面/对话框事件
|
|
215
|
+
for (const p of ctx.pages()) {
|
|
216
|
+
this.session.adopt(p, { activate: false });
|
|
217
|
+
}
|
|
218
|
+
void log("info", `attached context with ${ctx.pages().length} existing pages`);
|
|
219
|
+
ctx.on("page", (page) => {
|
|
220
|
+
const id = this.session.adopt(page, { activate: true });
|
|
221
|
+
this.recentPopups.push({ ts: Date.now(), url: page.url() });
|
|
222
|
+
if (this.recentPopups.length > MAX_RING)
|
|
223
|
+
this.recentPopups.shift();
|
|
224
|
+
void log("info", "new page adopted", { id, url: page.url() });
|
|
225
|
+
});
|
|
226
|
+
ctx.on("dialog", async (dialog) => {
|
|
227
|
+
const rec = {
|
|
228
|
+
ts: Date.now(),
|
|
229
|
+
type: dialog.type(),
|
|
230
|
+
message: dialog.message().slice(0, 500),
|
|
231
|
+
pageUrl: safeUrl(dialog.page()),
|
|
232
|
+
};
|
|
233
|
+
this.recentDialogs.push(rec);
|
|
234
|
+
if (this.recentDialogs.length > MAX_RING)
|
|
235
|
+
this.recentDialogs.shift();
|
|
236
|
+
void log("info", "dialog", rec);
|
|
237
|
+
try {
|
|
238
|
+
if (this.cfg.dialogPolicy === "accept") {
|
|
239
|
+
await dialog.accept();
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
await dialog.dismiss();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
/* 页面可能已跳转 */
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
ctx.on("download", (download) => {
|
|
250
|
+
const file = path.join(this.cfg.downloadDir, download.suggestedFilename() || `download-${uid()}`);
|
|
251
|
+
const rec = { ts: Date.now(), url: download.url(), path: file };
|
|
252
|
+
download
|
|
253
|
+
.saveAs(file)
|
|
254
|
+
.then(() => {
|
|
255
|
+
this.recentDownloads.push(rec);
|
|
256
|
+
})
|
|
257
|
+
.catch((e) => {
|
|
258
|
+
rec.error = e instanceof Error ? e.message : String(e);
|
|
259
|
+
this.recentDownloads.push(rec);
|
|
260
|
+
});
|
|
261
|
+
if (this.recentDownloads.length > MAX_RING)
|
|
262
|
+
this.recentDownloads.shift();
|
|
263
|
+
});
|
|
264
|
+
if (this.browser) {
|
|
265
|
+
this.browser.on("disconnected", () => {
|
|
266
|
+
// 懒重启:不在这里自动重启,等下次工具调用时 ensureReady 处理
|
|
267
|
+
this.state = "crashed";
|
|
268
|
+
this.crashedAt = Date.now();
|
|
269
|
+
this.lastError = this.lastError ?? "浏览器连接断开(手动关闭或崩溃)";
|
|
270
|
+
void log("warn", "browser disconnected; will lazy-restart on next call");
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
ctx.on("close", () => {
|
|
274
|
+
if (this.cfg.mode === "launch") {
|
|
275
|
+
this.state = "crashed";
|
|
276
|
+
this.crashedAt = Date.now();
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
// 事件就绪后再做会话恢复/认领
|
|
280
|
+
if (opts.adoptExisting) {
|
|
281
|
+
// connect 模式:不导航,只认领已有页面
|
|
282
|
+
const pages = this.session.listTabs();
|
|
283
|
+
if (pages.length > 0) {
|
|
284
|
+
void this.session.setActive(pages[0].id);
|
|
285
|
+
}
|
|
286
|
+
await this.recordBrowserPids();
|
|
287
|
+
return { restoredCount: 0 };
|
|
288
|
+
}
|
|
289
|
+
if (opts.restoreSession) {
|
|
290
|
+
const r = await this.restoreSession(ctx);
|
|
291
|
+
await this.recordBrowserPids();
|
|
292
|
+
return r;
|
|
293
|
+
}
|
|
294
|
+
return { restoredCount: 0 };
|
|
295
|
+
}
|
|
296
|
+
restoring = false;
|
|
297
|
+
async restoreSession(ctx) {
|
|
298
|
+
if (this.restoring)
|
|
299
|
+
return { restoredCount: 0 };
|
|
300
|
+
this.restoring = true;
|
|
301
|
+
let restoredCount = 0;
|
|
302
|
+
try {
|
|
303
|
+
const persisted = this.session.readPersisted();
|
|
304
|
+
const validTabs = persisted?.tabs.filter((t) => t.url && t.url !== "about:blank") ?? [];
|
|
305
|
+
const existing = ctx.pages();
|
|
306
|
+
if (validTabs.length === 0) {
|
|
307
|
+
// 全新会话:起始页
|
|
308
|
+
const page = existing[0] ?? (await ctx.newPage());
|
|
309
|
+
const id = this.session.adopt(page, { activate: true });
|
|
310
|
+
if (this.cfg.startUrl !== "about:blank") {
|
|
311
|
+
await safeGoto(page, this.cfg.startUrl, this.cfg.navTimeoutMs);
|
|
312
|
+
}
|
|
313
|
+
this.session.setActive(id);
|
|
314
|
+
return { restoredCount: 0 };
|
|
315
|
+
}
|
|
316
|
+
// 恢复:第一个标签用已有空白页,其余新建;失败容忍
|
|
317
|
+
for (let i = 0; i < validTabs.length; i++) {
|
|
318
|
+
const tab = validTabs[i];
|
|
319
|
+
let page;
|
|
320
|
+
if (i === 0 && existing.length > 0 && existing[0].url() === "about:blank") {
|
|
321
|
+
page = existing[0];
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
page = await ctx.newPage();
|
|
325
|
+
}
|
|
326
|
+
const id = this.session.adopt(page, { activate: tab.id === persisted?.activeId });
|
|
327
|
+
await safeGoto(page, tab.url, Math.min(15000, this.cfg.navTimeoutMs));
|
|
328
|
+
restoredCount++;
|
|
329
|
+
}
|
|
330
|
+
if (restoredCount > 0) {
|
|
331
|
+
void log("info", "session restored", { count: restoredCount });
|
|
332
|
+
}
|
|
333
|
+
return { restoredCount };
|
|
334
|
+
}
|
|
335
|
+
catch (e) {
|
|
336
|
+
void log("warn", "session restore partial failure", e);
|
|
337
|
+
return { restoredCount };
|
|
338
|
+
}
|
|
339
|
+
finally {
|
|
340
|
+
this.restoring = false;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
// ---------------- 查询与关闭 ----------------
|
|
344
|
+
getContext() {
|
|
345
|
+
if (!this.context)
|
|
346
|
+
throw new ToolError("not_ready", "浏览器尚未启动", "这是内部错误,请重试一次");
|
|
347
|
+
return this.context;
|
|
348
|
+
}
|
|
349
|
+
pageById(id) {
|
|
350
|
+
return this.session.get(id);
|
|
351
|
+
}
|
|
352
|
+
/** 最近 N ms 内出现的新弹窗(供点击结果提示) */
|
|
353
|
+
popupsSince(ts) {
|
|
354
|
+
return this.recentPopups.filter((p) => p.ts >= ts).map((p) => ({ url: p.url }));
|
|
355
|
+
}
|
|
356
|
+
dialogsSince(ts) {
|
|
357
|
+
return this.recentDialogs.filter((d) => d.ts >= ts);
|
|
358
|
+
}
|
|
359
|
+
downloadsSince(ts) {
|
|
360
|
+
return this.recentDownloads.filter((d) => d.ts >= ts);
|
|
361
|
+
}
|
|
362
|
+
async killOwnBrowser() {
|
|
363
|
+
try {
|
|
364
|
+
if (this.browser) {
|
|
365
|
+
await withTimeout(this.browser.close(), 8000, "关闭浏览器");
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
/* 忽略 */
|
|
370
|
+
}
|
|
371
|
+
if (this.cfg.mode === "launch") {
|
|
372
|
+
// 双保险:确保没有残留进程占用 profile
|
|
373
|
+
await this.killOrphanByProfile();
|
|
374
|
+
}
|
|
375
|
+
this.browser = null;
|
|
376
|
+
this.context = null;
|
|
377
|
+
}
|
|
378
|
+
async shutdown() {
|
|
379
|
+
await this.session.flush().catch(() => { });
|
|
380
|
+
if (this.cfg.mode === "connect") {
|
|
381
|
+
// 外部浏览器不关,只断开
|
|
382
|
+
try {
|
|
383
|
+
await this.browser?.close();
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
/* connectOverCDP 的 close 只断开连接 */
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
else {
|
|
390
|
+
await this.killOwnBrowser();
|
|
391
|
+
}
|
|
392
|
+
this.state = "stopped";
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
function safeUrl(page) {
|
|
396
|
+
try {
|
|
397
|
+
return page?.url() ?? "";
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
return "";
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
async function safeGoto(page, url, timeoutMs) {
|
|
404
|
+
try {
|
|
405
|
+
await withTimeout(page.goto(url, { waitUntil: "domcontentloaded", timeout: timeoutMs }), timeoutMs + 5000, "导航 " + url);
|
|
406
|
+
}
|
|
407
|
+
catch (e) {
|
|
408
|
+
void log("warn", `restore goto failed: ${url}`, e);
|
|
409
|
+
}
|
|
410
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// 配置:默认值 → 配置文件 → 环境变量 → 命令行参数(后者覆盖前者)
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
+
function parseBool(v) {
|
|
6
|
+
if (v === undefined || v === "")
|
|
7
|
+
return undefined;
|
|
8
|
+
return !["0", "false", "no", "off"].includes(v.toLowerCase());
|
|
9
|
+
}
|
|
10
|
+
function parseViewport(v) {
|
|
11
|
+
if (v === undefined || v === "")
|
|
12
|
+
return undefined;
|
|
13
|
+
if (v.toLowerCase() === "max" || v === "null")
|
|
14
|
+
return null;
|
|
15
|
+
const m = v.match(/^(\d+)x(\d+)$/);
|
|
16
|
+
if (!m)
|
|
17
|
+
return undefined;
|
|
18
|
+
return { width: Number(m[1]), height: Number(m[2]) };
|
|
19
|
+
}
|
|
20
|
+
/** 极简 argv 解析:--key value / --key=value / --flag */
|
|
21
|
+
function parseArgv(argv) {
|
|
22
|
+
const out = {};
|
|
23
|
+
for (let i = 0; i < argv.length; i++) {
|
|
24
|
+
const a = argv[i];
|
|
25
|
+
if (!a.startsWith("--"))
|
|
26
|
+
continue;
|
|
27
|
+
const eq = a.indexOf("=");
|
|
28
|
+
if (eq > 0) {
|
|
29
|
+
out[a.slice(2, eq)] = a.slice(eq + 1);
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
const key = a.slice(2);
|
|
33
|
+
const next = argv[i + 1];
|
|
34
|
+
if (next !== undefined && !next.startsWith("--")) {
|
|
35
|
+
out[key] = next;
|
|
36
|
+
i++;
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
out[key] = true;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
export function loadConfig(argv = process.argv.slice(2)) {
|
|
46
|
+
const args = parseArgv(argv);
|
|
47
|
+
const env = process.env;
|
|
48
|
+
const home = homedir();
|
|
49
|
+
const stateDir = String(args["state-dir"] ?? env.BROWSER_MCP_STATE_DIR ?? path.join(home, ".browser-mcp"));
|
|
50
|
+
const defaultProfile = path.join(stateDir, "profile");
|
|
51
|
+
// 配置文件(可整体覆盖默认值;同步读,启动时只跑一次)
|
|
52
|
+
const cfgFile = path.join(stateDir, "config.json");
|
|
53
|
+
let fileCfg = {};
|
|
54
|
+
try {
|
|
55
|
+
if (existsSync(cfgFile)) {
|
|
56
|
+
fileCfg = JSON.parse(readFileSync(cfgFile, "utf8"));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
fileCfg = {}; // 配置文件损坏时按默认值启动,不阻塞
|
|
61
|
+
}
|
|
62
|
+
const cfg = {
|
|
63
|
+
mode: "launch",
|
|
64
|
+
cdpUrl: null,
|
|
65
|
+
profileDir: defaultProfile,
|
|
66
|
+
channels: ["chrome", "msedge"],
|
|
67
|
+
executablePath: null,
|
|
68
|
+
headless: false,
|
|
69
|
+
viewport: null,
|
|
70
|
+
locale: "zh-CN",
|
|
71
|
+
stateDir,
|
|
72
|
+
logDir: path.join(stateDir, "logs"),
|
|
73
|
+
downloadDir: path.join(stateDir, "downloads"),
|
|
74
|
+
navTimeoutMs: 30000,
|
|
75
|
+
actionTimeoutMs: 15000,
|
|
76
|
+
resultMaxChars: 30000,
|
|
77
|
+
snapshotMaxElements: 400,
|
|
78
|
+
dialogPolicy: "accept",
|
|
79
|
+
startUrl: "about:blank",
|
|
80
|
+
extraArgs: [],
|
|
81
|
+
};
|
|
82
|
+
const apply = (patch) => {
|
|
83
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
84
|
+
if (v === undefined || v === null || v === "")
|
|
85
|
+
continue;
|
|
86
|
+
cfg[k] = v;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
// 文件配置
|
|
90
|
+
apply(fileCfg);
|
|
91
|
+
// 环境变量
|
|
92
|
+
apply({
|
|
93
|
+
mode: parseBool(env.BROWSER_MCP_CONNECT) === true ? "connect" : undefined,
|
|
94
|
+
cdpUrl: env.BROWSER_MCP_CDP_URL,
|
|
95
|
+
profileDir: env.BROWSER_MCP_PROFILE,
|
|
96
|
+
channels: env.BROWSER_MCP_CHANNELS ? env.BROWSER_MCP_CHANNELS.split(",").map((s) => s.trim()) : undefined,
|
|
97
|
+
executablePath: env.BROWSER_MCP_EXECUTABLE,
|
|
98
|
+
headless: parseBool(env.BROWSER_MCP_HEADLESS),
|
|
99
|
+
viewport: parseViewport(env.BROWSER_MCP_VIEWPORT),
|
|
100
|
+
locale: env.BROWSER_MCP_LOCALE,
|
|
101
|
+
navTimeoutMs: env.BROWSER_MCP_NAV_TIMEOUT ? Number(env.BROWSER_MCP_NAV_TIMEOUT) : undefined,
|
|
102
|
+
actionTimeoutMs: env.BROWSER_MCP_ACTION_TIMEOUT ? Number(env.BROWSER_MCP_ACTION_TIMEOUT) : undefined,
|
|
103
|
+
dialogPolicy: env.BROWSER_MCP_DIALOGS,
|
|
104
|
+
startUrl: env.BROWSER_MCP_START_URL,
|
|
105
|
+
});
|
|
106
|
+
// 命令行参数(优先级最高;MCP 客户端注册时可用 args 传入)
|
|
107
|
+
apply({
|
|
108
|
+
mode: args["connect"] === true || (typeof args["cdp-url"] === "string" && args["cdp-url"] !== "") ? "connect" : undefined,
|
|
109
|
+
cdpUrl: typeof args["cdp-url"] === "string" ? args["cdp-url"] : args["connect"] === true ? "http://127.0.0.1:9222" : undefined,
|
|
110
|
+
profileDir: typeof args["profile"] === "string" ? args["profile"] : undefined,
|
|
111
|
+
channels: typeof args["channels"] === "string" ? String(args["channels"]).split(",").map((s) => s.trim()) : undefined,
|
|
112
|
+
executablePath: typeof args["executable"] === "string" ? args["executable"] : undefined,
|
|
113
|
+
headless: args["headless"] === true ? true : args["headed"] === true ? false : undefined,
|
|
114
|
+
viewport: parseViewport(typeof args["viewport"] === "string" ? args["viewport"] : undefined),
|
|
115
|
+
locale: typeof args["locale"] === "string" ? args["locale"] : undefined,
|
|
116
|
+
navTimeoutMs: typeof args["nav-timeout"] === "string" ? Number(args["nav-timeout"]) : undefined,
|
|
117
|
+
actionTimeoutMs: typeof args["action-timeout"] === "string" ? Number(args["action-timeout"]) : undefined,
|
|
118
|
+
dialogPolicy: typeof args["dialogs"] === "string" ? args["dialogs"] : undefined,
|
|
119
|
+
startUrl: typeof args["start-url"] === "string" ? args["start-url"] : undefined,
|
|
120
|
+
extraArgs: typeof args["extra-args"] === "string" ? String(args["extra-args"]).split(" ").filter(Boolean) : undefined,
|
|
121
|
+
});
|
|
122
|
+
if (cfg.mode === "connect" && !cfg.cdpUrl)
|
|
123
|
+
cfg.cdpUrl = "http://127.0.0.1:9222";
|
|
124
|
+
return cfg;
|
|
125
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// 错误整形:把底层异常翻译成 agent 能直接行动的结构化信息
|
|
2
|
+
import { log } from "./util.js";
|
|
3
|
+
export class ToolError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
hint;
|
|
6
|
+
constructor(code, message, hint) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.hint = hint;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function shapeError(e) {
|
|
13
|
+
if (e instanceof ToolError) {
|
|
14
|
+
return { code: e.code, message: e.message, hint: e.hint };
|
|
15
|
+
}
|
|
16
|
+
const raw = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
17
|
+
const msg = raw.slice(0, 500);
|
|
18
|
+
void log("error", "action failed", raw);
|
|
19
|
+
if (/Timeout.*exceeded|TimeoutError/i.test(raw)) {
|
|
20
|
+
return {
|
|
21
|
+
code: "timeout",
|
|
22
|
+
message: msg,
|
|
23
|
+
hint: "元素未出现或不可操作。常见原因:①页面还在加载,先调 browser_wait;②元素在 iframe 里,用 browser_snapshot 查看最新结构;③选择器过期,重新 browser_snapshot 拿最新 ref。",
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
if (/Target closed|Target page, context or browser has been closed|Browser closed|browser has been closed/i.test(raw)) {
|
|
27
|
+
return {
|
|
28
|
+
code: "browser_closed",
|
|
29
|
+
message: msg,
|
|
30
|
+
hint: "浏览器连接已断开(可能被手动关闭或崩溃)。下次工具调用会自动重启浏览器并恢复会话,直接重试即可;旧 ref 已全部失效,请重新 browser_snapshot。",
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
if (/EBUSY|EPERM|accessdenied|singleton/i.test(raw)) {
|
|
34
|
+
return {
|
|
35
|
+
code: "profile_locked",
|
|
36
|
+
message: msg,
|
|
37
|
+
hint: "profile 目录被占用(可能有残留 Chrome 进程)。系统会尝试清理后重试;若仍失败,请手动关闭使用该 profile 的 Chrome。",
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
if (/Execution context was destroyed|navigation/i.test(raw)) {
|
|
41
|
+
return {
|
|
42
|
+
code: "page_navigated",
|
|
43
|
+
message: msg,
|
|
44
|
+
hint: "操作过程中页面发生了跳转。请重新 browser_snapshot 后用新 ref 重试。",
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
code: "unknown",
|
|
49
|
+
message: msg,
|
|
50
|
+
hint: "未知错误。可调用 browser_get_info 查看浏览器健康状态,或重新 browser_snapshot 获取当前页面。",
|
|
51
|
+
};
|
|
52
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 入口:stdio MCP server。日志只进文件/stderr,stdout 专用于 MCP 协议。
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
5
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
6
|
+
import { loadConfig } from "./config.js";
|
|
7
|
+
import { BrowserManager } from "./browserManager.js";
|
|
8
|
+
import { RefRegistry } from "./snapshot.js";
|
|
9
|
+
import { registerTools } from "./tools.js";
|
|
10
|
+
import { initLogging, log } from "./util.js";
|
|
11
|
+
// 版本号只从 package.json 取一处,避免发版时漏改。
|
|
12
|
+
// dist/index.js 的上一级就是包根目录。
|
|
13
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
14
|
+
async function main() {
|
|
15
|
+
// --version (直接输出后退出,此时不进入 MCP 协议,可安全用 stdout)
|
|
16
|
+
if (process.argv.includes("--version") || process.argv.includes("-v")) {
|
|
17
|
+
process.stdout.write(`${pkg.version}\n`);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
// --help / --version
|
|
21
|
+
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
22
|
+
process.stderr.write(`browser-ref-mcp ${pkg.version} — 给 agent 用的可靠浏览器控制 MCP server
|
|
23
|
+
|
|
24
|
+
用法: npx browser-ref-mcp [选项]
|
|
25
|
+
--cdp-url <url> connect 模式:连接已开调试端口的浏览器(如 http://127.0.0.1:9222)
|
|
26
|
+
--headless 无头模式(默认有头)
|
|
27
|
+
--profile <dir> 指定 profile 用户数据目录(默认 ~/.browser-mcp/profile)
|
|
28
|
+
--channels <list> 浏览器渠道回退链(默认 chrome,msedge)
|
|
29
|
+
--executable <path> 直接指定浏览器可执行文件
|
|
30
|
+
--viewport WxH 固定视口(默认有头时跟随窗口大小)
|
|
31
|
+
--start-url <url> 全新会话的起始页
|
|
32
|
+
--dialogs accept|dismiss 对话框策略(默认 accept)
|
|
33
|
+
--state-dir <dir> 状态目录(默认 ~/.browser-mcp)
|
|
34
|
+
配置文件: ~/.browser-mcp/config.json;环境变量: BROWSER_MCP_*(详见 README)
|
|
35
|
+
`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const cfg = loadConfig();
|
|
39
|
+
await initLogging(cfg.logDir);
|
|
40
|
+
await log("info", "server starting", { pid: process.pid, mode: cfg.mode, headless: cfg.headless, profile: cfg.profileDir });
|
|
41
|
+
const manager = new BrowserManager(cfg);
|
|
42
|
+
const registry = new RefRegistry();
|
|
43
|
+
const server = new Server({ name: "browser-ref-mcp", version: pkg.version }, { capabilities: { tools: {} } });
|
|
44
|
+
registerTools(server, manager, registry);
|
|
45
|
+
// 优雅退出:关闭浏览器防止僵尸进程;connect 模式只断开
|
|
46
|
+
let shuttingDown = false;
|
|
47
|
+
const shutdown = async (reason) => {
|
|
48
|
+
if (shuttingDown)
|
|
49
|
+
return;
|
|
50
|
+
shuttingDown = true;
|
|
51
|
+
await log("info", `shutting down (${reason})`);
|
|
52
|
+
await manager.shutdown();
|
|
53
|
+
process.exit(0);
|
|
54
|
+
};
|
|
55
|
+
process.on("SIGINT", () => void shutdown("SIGINT"));
|
|
56
|
+
process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
|
57
|
+
process.on("SIGHUP", () => void shutdown("SIGHUP"));
|
|
58
|
+
process.on("exit", () => {
|
|
59
|
+
// exit 回调里不能异步;launch 模式下浏览器是子进程,进程死亡后由系统回收
|
|
60
|
+
// 若有残留,下次启动时 killOrphanByProfile 会清理
|
|
61
|
+
});
|
|
62
|
+
process.on("unhandledRejection", (e) => {
|
|
63
|
+
void log("error", "unhandledRejection", e);
|
|
64
|
+
});
|
|
65
|
+
process.on("uncaughtException", (e) => {
|
|
66
|
+
void log("error", "uncaughtException", e);
|
|
67
|
+
// 不退出:MCP server 存活优先,工具调用层已有兜底
|
|
68
|
+
});
|
|
69
|
+
const transport = new StdioServerTransport();
|
|
70
|
+
await server.connect(transport);
|
|
71
|
+
await log("info", "stdio transport connected, serving tools");
|
|
72
|
+
}
|
|
73
|
+
main().catch(async (e) => {
|
|
74
|
+
await log("error", "fatal startup error", e).catch(() => { });
|
|
75
|
+
process.stderr.write(`browser-ref-mcp 启动失败: ${e instanceof Error ? e.stack : String(e)}\n`);
|
|
76
|
+
process.exit(1);
|
|
77
|
+
});
|