browser-ref-mcp 0.0.0-stage → 0.1.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/dist/tools.js ADDED
@@ -0,0 +1,498 @@
1
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
2
+ import { snapshotPage } from "./snapshot.js";
3
+ import { doClick, doEvaluate, doHover, doPressKey, doScreenshot, doScroll, doSelectOption, doType, doWait, formatAfter, } from "./actions.js";
4
+ import { ToolError, shapeError } from "./errors.js";
5
+ import { safeStringify, truncate } from "./util.js";
6
+ function text(content) {
7
+ return { content: [{ type: "text", text: content }] };
8
+ }
9
+ function textError(shape) {
10
+ const lines = [`❌ [${shape.code}] ${shape.message}`];
11
+ if (shape.hint)
12
+ lines.push(`💡 ${shape.hint}`);
13
+ return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
14
+ }
15
+ const STR = { type: "string" };
16
+ const NUM = { type: "number" };
17
+ const BOOL = { type: "boolean" };
18
+ function strEnum(values) {
19
+ return { type: "string", enum: values };
20
+ }
21
+ export function registerTools(server, manager, registry) {
22
+ // ---------- 公共助手 ----------
23
+ async function requireActivePage() {
24
+ await manager.ensureReady();
25
+ const ctx = manager.getContext();
26
+ const page = manager.session.getActive();
27
+ if (page) {
28
+ const all = manager.session.listTabs();
29
+ const active = all.find((t) => t.active) ?? all[0];
30
+ if (active)
31
+ return { page, pageId: active.id, created: false };
32
+ }
33
+ const newPage = await ctx.newPage();
34
+ const pageId = manager.session.adopt(newPage, { activate: true });
35
+ return { page: newPage, pageId, created: true };
36
+ }
37
+ function activePageId() {
38
+ return manager.session.listTabs().find((t) => t.active)?.id;
39
+ }
40
+ async function attachSnapshot(out, page, args, filter = "balanced") {
41
+ if (args.snapshot === false)
42
+ return;
43
+ const pageId = activePageId() ?? "?";
44
+ const snap = await snapshotPage(page, pageId, registry, { filter });
45
+ out.push("", "── 最新快照 ──", snap.text);
46
+ }
47
+ function capOut(s) {
48
+ return s.length > manager.cfg.resultMaxChars
49
+ ? s.slice(0, manager.cfg.resultMaxChars) + `\n…(结果超过 ${manager.cfg.resultMaxChars} 字符被截断,请缩小查询范围)`
50
+ : s;
51
+ }
52
+ // ---------- 工具定义 ----------
53
+ const tools = [
54
+ {
55
+ name: "browser_navigate",
56
+ description: "导航到 URL,返回后自动附带页面交互元素快照(带 [eN] ref 编号,可直接用于 click/type)。缺协议时自动补 https://。",
57
+ inputSchema: {
58
+ type: "object",
59
+ properties: {
60
+ url: { ...STR, description: "目标 URL" },
61
+ newTab: { ...BOOL, description: "是否在新标签页打开(默认 false,当前页导航)" },
62
+ timeoutMs: { ...NUM, description: "导航超时毫秒数(默认 30000)" },
63
+ snapshot: { ...BOOL, description: "是否在结果中附快照(默认 true)" },
64
+ },
65
+ required: ["url"],
66
+ additionalProperties: false,
67
+ },
68
+ needsBrowser: true,
69
+ handler: async (args) => {
70
+ let url = String(args.url).trim();
71
+ if (!/^https?:\/\//i.test(url) && !/^file:\/\//i.test(url) && !/^about:/i.test(url)) {
72
+ url = "https://" + url;
73
+ }
74
+ const ctx = manager.getContext();
75
+ let page;
76
+ let pageId;
77
+ if (args.newTab === true) {
78
+ page = await ctx.newPage();
79
+ pageId = manager.session.adopt(page, { activate: true });
80
+ }
81
+ else {
82
+ const active = await requireActivePage();
83
+ page = active.page;
84
+ pageId = active.pageId;
85
+ }
86
+ registry.clearPage(pageId); // 导航后旧 ref 作废
87
+ const out = [];
88
+ const timeout = typeof args.timeoutMs === "number" ? args.timeoutMs : manager.cfg.navTimeoutMs;
89
+ try {
90
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout });
91
+ }
92
+ catch (e) {
93
+ const msg = e instanceof Error ? e.message : String(e);
94
+ if (/Timeout/i.test(msg)) {
95
+ out.push(`⚠️ 导航超时(${timeout}ms),页面可能仍在加载。当前 URL: ${page.url()}`);
96
+ out.push("💡 可直接 browser_snapshot 看看已加载的部分,或用 browser_wait {idle:true} 再等网络空闲。");
97
+ }
98
+ else {
99
+ throw e;
100
+ }
101
+ }
102
+ manager.session.markDirty();
103
+ const title = await page.title().catch(() => "");
104
+ out.push(`✅ 已打开: ${title || "(无标题)"} — ${page.url()}`);
105
+ const popups = manager.popupsSince(Date.now() - 2000);
106
+ for (const p of popups)
107
+ out.push(`🪟 检测到新标签页 → ${p.url}`);
108
+ await attachSnapshot(out, page, args);
109
+ return text(capOut(out.join("\n")));
110
+ },
111
+ },
112
+ {
113
+ name: "browser_snapshot",
114
+ description: '获取当前页面语义快照:交互元素带 [eN] ref 编号(iframe 内容已拍平)。支持 rootRef(只看某元素子树)、selector、filter:"interactive" 只看交互元素。',
115
+ inputSchema: {
116
+ type: "object",
117
+ properties: {
118
+ filter: strEnum(["balanced", "interactive", "text"]),
119
+ rootRef: { ...STR, description: "只快照该 ref 元素的子树" },
120
+ selector: { ...STR, description: "只快照匹配该 CSS 选择器的子树(主文档)" },
121
+ maxElements: { ...NUM, description: "最多输出行数(默认 400)" },
122
+ },
123
+ additionalProperties: false,
124
+ },
125
+ needsBrowser: true,
126
+ handler: async (args) => {
127
+ const { page } = await requireActivePage();
128
+ const pageId = activePageId() ?? "?";
129
+ const snap = await snapshotPage(page, pageId, registry, {
130
+ filter: args.filter,
131
+ rootRef: args.rootRef,
132
+ rootSelector: args.selector,
133
+ maxElements: typeof args.maxElements === "number" ? args.maxElements : undefined,
134
+ title: await page.title().catch(() => ""),
135
+ });
136
+ return text(capOut(snap.text));
137
+ },
138
+ },
139
+ {
140
+ name: "browser_click",
141
+ description: "点击元素(优先用快照里的 ref)。自动等待可操作、自动重解析失效 ref、点击后自动附最新快照。特殊对话框会自动处理并上报。",
142
+ inputSchema: {
143
+ type: "object",
144
+ properties: {
145
+ ref: { ...STR, description: "快照中的 [eN] 编号" },
146
+ selector: { ...STR, description: "CSS 选择器(ref 不可用时的兜底)" },
147
+ text: { ...STR, description: "按可见文本匹配" },
148
+ button: strEnum(["left", "right", "middle"]),
149
+ doubleClick: { ...BOOL },
150
+ timeoutMs: { ...NUM },
151
+ snapshot: { ...BOOL, description: "点击后是否附快照(默认 true)" },
152
+ },
153
+ additionalProperties: false,
154
+ },
155
+ needsBrowser: true,
156
+ handler: async (args) => {
157
+ const { page } = await requireActivePage();
158
+ const { target, after } = await doClick(manager, page, registry, args);
159
+ const out = [];
160
+ out.push("✅ 已点击。" + (target.notes.length ? "\n" + target.notes.join("\n") : ""));
161
+ const afterText = formatAfter(after);
162
+ if (afterText)
163
+ out.push(afterText);
164
+ await attachSnapshot(out, page, args);
165
+ return text(capOut(out.join("\n")));
166
+ },
167
+ },
168
+ {
169
+ name: "browser_type",
170
+ description: "向输入框输入文本(先清空再输入)。submit:true 时回车提交。适用于 input/textarea/contenteditable。",
171
+ inputSchema: {
172
+ type: "object",
173
+ properties: {
174
+ ref: { ...STR },
175
+ selector: { ...STR },
176
+ text: { ...STR, description: "要输入的文本" },
177
+ submit: { ...BOOL, description: "输入后按 Enter(默认 false)" },
178
+ clear: { ...BOOL, description: "是否先清空(默认 true;false 则追加)" },
179
+ timeoutMs: { ...NUM },
180
+ },
181
+ required: ["text"],
182
+ additionalProperties: false,
183
+ },
184
+ needsBrowser: true,
185
+ handler: async (args) => {
186
+ const { page } = await requireActivePage();
187
+ const { target, after } = await doType(manager, page, registry, args);
188
+ const out = [];
189
+ out.push(`✅ 已输入: ${JSON.stringify(truncate(String(args.text), 80))}` + (args.submit ? " 并回车提交。" : ".") + (target.notes.length ? "\n" + target.notes.join("\n") : ""));
190
+ const afterText = formatAfter(after);
191
+ if (afterText)
192
+ out.push(afterText);
193
+ await attachSnapshot(out, page, args);
194
+ return text(capOut(out.join("\n")));
195
+ },
196
+ },
197
+ {
198
+ name: "browser_press_key",
199
+ description: '按下键盘按键,如 Enter / Tab / ArrowDown / "Control+a"。带 ref 时先聚焦该元素。',
200
+ inputSchema: {
201
+ type: "object",
202
+ properties: {
203
+ key: { ...STR, description: "键名,如 Enter、Escape、ArrowDown、Control+a" },
204
+ ref: { ...STR, description: "先聚焦此元素再按键" },
205
+ },
206
+ required: ["key"],
207
+ additionalProperties: false,
208
+ },
209
+ needsBrowser: true,
210
+ handler: async (args) => {
211
+ const { page } = await requireActivePage();
212
+ const { after } = await doPressKey(manager, page, registry, args);
213
+ const out = [`✅ 已按下 ${args.key}。`];
214
+ const afterText = formatAfter(after);
215
+ if (afterText)
216
+ out.push(afterText);
217
+ return text(capOut(out.join("\n")));
218
+ },
219
+ },
220
+ {
221
+ name: "browser_select_option",
222
+ description: "在下拉框(select)中选中选项。values 可为 value 或可见 label,自动两轮匹配。",
223
+ inputSchema: {
224
+ type: "object",
225
+ properties: {
226
+ ref: { ...STR },
227
+ selector: { ...STR },
228
+ values: { type: "array", items: STR, description: "要选中的 value/label 列表" },
229
+ timeoutMs: { ...NUM },
230
+ },
231
+ required: ["values"],
232
+ additionalProperties: false,
233
+ },
234
+ needsBrowser: true,
235
+ handler: async (args) => {
236
+ const { page } = await requireActivePage();
237
+ const { selected, after } = await doSelectOption(manager, page, registry, args);
238
+ const out = [`✅ 已选中: ${JSON.stringify(selected)}`];
239
+ const afterText = formatAfter(after);
240
+ if (afterText)
241
+ out.push(afterText);
242
+ await attachSnapshot(out, page, args);
243
+ return text(capOut(out.join("\n")));
244
+ },
245
+ },
246
+ {
247
+ name: "browser_hover",
248
+ description: "鼠标悬停到元素上(触发悬浮菜单/tooltip)。",
249
+ inputSchema: {
250
+ type: "object",
251
+ properties: {
252
+ ref: { ...STR },
253
+ selector: { ...STR },
254
+ timeoutMs: { ...NUM },
255
+ },
256
+ additionalProperties: false,
257
+ },
258
+ needsBrowser: true,
259
+ handler: async (args) => {
260
+ const { page } = await requireActivePage();
261
+ const { target, after } = await doHover(manager, page, registry, args);
262
+ const out = ["✅ 已悬停。" + (target.notes.length ? "\n" + target.notes.join("\n") : "")];
263
+ const afterText = formatAfter(after);
264
+ if (afterText)
265
+ out.push(afterText);
266
+ await attachSnapshot(out, page, args);
267
+ return text(capOut(out.join("\n")));
268
+ },
269
+ },
270
+ {
271
+ name: "browser_scroll",
272
+ description: "滚动页面或指定滚动容器(带 ref 时滚动该容器)。方向 + 像素量。",
273
+ inputSchema: {
274
+ type: "object",
275
+ properties: {
276
+ direction: strEnum(["up", "down", "left", "right"]),
277
+ amount: { ...NUM, description: "滚动像素(默认 600)" },
278
+ ref: { ...STR, description: "滚动该容器(快照中带 [可滚动] 标记的元素)" },
279
+ },
280
+ required: ["direction"],
281
+ additionalProperties: false,
282
+ },
283
+ needsBrowser: true,
284
+ handler: async (args) => {
285
+ const { page } = await requireActivePage();
286
+ const { after } = await doScroll(manager, page, registry, args);
287
+ const out = ["✅ 已滚动。"];
288
+ const afterText = formatAfter(after);
289
+ if (afterText)
290
+ out.push(afterText);
291
+ return text(capOut(out.join("\n")));
292
+ },
293
+ },
294
+ {
295
+ name: "browser_screenshot",
296
+ description: "截屏并保存到本地,返回图片(供多模态查看)。可整页、可视区或单元素(ref)。",
297
+ inputSchema: {
298
+ type: "object",
299
+ properties: {
300
+ fullPage: { ...BOOL, description: "整页截图(默认只截可视区)" },
301
+ ref: { ...STR, description: "只截该元素" },
302
+ filename: { ...STR, description: "文件名(不含扩展名,默认时间戳)" },
303
+ },
304
+ additionalProperties: false,
305
+ },
306
+ needsBrowser: true,
307
+ handler: async (args) => {
308
+ const { page } = await requireActivePage();
309
+ const shot = await doScreenshot(manager, page, registry, args);
310
+ return {
311
+ content: [
312
+ { type: "image", data: shot.base64, mimeType: shot.mimeType },
313
+ { type: "text", text: `✅ 截图已保存 → ${shot.file}` },
314
+ ],
315
+ };
316
+ },
317
+ },
318
+ {
319
+ name: "browser_evaluate",
320
+ description: "逃生舱:在页面里执行 JS 并返回 JSON 可序列化结果。传函数字符串如 `() => document.title` 或 `() => {...}`;带 ref 时在该元素上执行(`(el, ) => el.value`)。",
321
+ inputSchema: {
322
+ type: "object",
323
+ properties: {
324
+ js: { ...STR, description: "函数字符串,如 `() => document.querySelector('#app')?.innerText.slice(0,2000)`" },
325
+ ref: { ...STR, description: "在该元素上执行,回调第一个参数是元素" },
326
+ },
327
+ required: ["js"],
328
+ additionalProperties: false,
329
+ },
330
+ needsBrowser: true,
331
+ handler: async (args) => {
332
+ const { page } = await requireActivePage();
333
+ const { result } = await doEvaluate(manager, page, registry, args);
334
+ const s = safeStringify(result, 8000);
335
+ return text(capOut(`✅ 执行结果:\n${s === undefined ? "undefined" : s}`));
336
+ },
337
+ },
338
+ {
339
+ name: "browser_wait",
340
+ description: '等待条件成立:timeMs 固定时长 / text 文本出现 / selector 元素出现 / url 跳转 / idle 网络空闲。可组合。',
341
+ inputSchema: {
342
+ type: "object",
343
+ properties: {
344
+ timeMs: { ...NUM },
345
+ text: { ...STR, description: "等待该文本出现在页面上" },
346
+ selector: { ...STR },
347
+ url: { ...STR, description: "等待 URL 变为该模式" },
348
+ idle: { ...BOOL, description: "等待网络空闲(最长 15s)" },
349
+ timeoutMs: { ...NUM, description: "等待超时(默认 15000)" },
350
+ },
351
+ additionalProperties: false,
352
+ },
353
+ needsBrowser: true,
354
+ handler: async (args) => {
355
+ const { page } = await requireActivePage();
356
+ const { waited, notes } = await doWait(manager, page, args);
357
+ const out = [`✅ ${waited}。`];
358
+ for (const n of notes)
359
+ out.push(`⚠️ ${n}`);
360
+ return text(capOut(out.join("\n")));
361
+ },
362
+ },
363
+ {
364
+ name: "browser_tabs",
365
+ description: "多标签管理:list 列出 / new 新建 / select 切换(按 list 显示的 index 或 id)/ close 关闭。",
366
+ inputSchema: {
367
+ type: "object",
368
+ properties: {
369
+ action: strEnum(["list", "new", "select", "close"]),
370
+ url: { ...STR, description: "new 时打开的 URL(可选)" },
371
+ index: { ...NUM, description: "select/close 的目标标签序号(见 list 输出,0 起)" },
372
+ id: { ...STR, description: "select/close 的目标标签 pageId" },
373
+ },
374
+ required: ["action"],
375
+ additionalProperties: false,
376
+ },
377
+ needsBrowser: true,
378
+ handler: async (args) => {
379
+ const action = String(args.action);
380
+ const ctx = manager.getContext();
381
+ const tabs = manager.session.listTabs();
382
+ if (action === "list") {
383
+ const lines = tabs.map((t, i) => `${t.active ? "▶" : " "} [${i}] id=${t.id} ${t.title || "(无标题)"} — ${t.url}`);
384
+ return text(capOut(`共 ${tabs.length} 个标签页:\n${lines.join("\n") || "(无)"}`));
385
+ }
386
+ if (action === "new") {
387
+ const page = await ctx.newPage();
388
+ const id = manager.session.adopt(page, { activate: true });
389
+ const url = typeof args.url === "string" && args.url.trim() ? args.url.trim() : "about:blank";
390
+ if (url !== "about:blank")
391
+ await page.goto(url, { waitUntil: "domcontentloaded" }).catch(() => { });
392
+ manager.session.markDirty();
393
+ return text(`✅ 新标签页已打开 → ${url}(id=${id})`);
394
+ }
395
+ // select / close 需要目标
396
+ const byIndex = typeof args.index === "number" ? tabs[args.index]?.id : undefined;
397
+ const targetId = (typeof args.id === "string" && args.id) || byIndex;
398
+ if (!targetId) {
399
+ throw new ToolError("missing_target", "select/close 需要指定 index 或 id", "先 browser_tabs {action:'list'} 查看标签列表");
400
+ }
401
+ const targetPage = manager.pageById(targetId);
402
+ if (!targetPage) {
403
+ throw new ToolError("not_found", `标签 ${targetId} 不存在或已关闭`, "先 browser_tabs {action:'list'} 查看标签列表");
404
+ }
405
+ if (action === "select") {
406
+ manager.session.setActive(targetId);
407
+ const title = await targetPage.title().catch(() => "");
408
+ return text(`✅ 已切换到标签: ${title} — ${targetPage.url()}`);
409
+ }
410
+ // close
411
+ await targetPage.close().catch(() => { });
412
+ manager.session.remove(targetId);
413
+ manager.session.markDirty();
414
+ const remaining = manager.session.listTabs();
415
+ if (remaining.length === 0) {
416
+ const page = await ctx.newPage();
417
+ manager.session.adopt(page, { activate: true });
418
+ return text("✅ 已关闭最后一个标签,已新建空白页。");
419
+ }
420
+ return text(`✅ 已关闭标签(id=${targetId}),剩余 ${remaining.length} 个。`);
421
+ },
422
+ },
423
+ {
424
+ name: "browser_get_info",
425
+ description: "查询浏览器健康状态:模式、标签列表、重启次数、最近错误/对话框/下载。不会启动浏览器。",
426
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
427
+ needsBrowser: false,
428
+ handler: async () => {
429
+ const tabs = manager.session.listTabs();
430
+ const info = {
431
+ mode: manager.cfg.mode,
432
+ state: manager.state,
433
+ headless: manager.cfg.headless,
434
+ channels: manager.cfg.channels,
435
+ profileDir: manager.cfg.profileDir,
436
+ restartCount: manager.restartCount,
437
+ launchedAt: manager.launchedAt ? new Date(manager.launchedAt).toISOString() : null,
438
+ lastError: manager.lastError,
439
+ browserPids: manager.browserPids,
440
+ tabs: tabs.map((t, i) => ({ index: i, id: t.id, active: t.active, title: t.title, url: t.url })),
441
+ recentDialogs: manager.recentDialogs.slice(-5),
442
+ recentDownloads: manager.recentDownloads.slice(-5),
443
+ registryRefs: registry.size,
444
+ logDir: manager.cfg.logDir,
445
+ };
446
+ return text(safeStringify(info, 6000) ?? "{}");
447
+ },
448
+ },
449
+ {
450
+ name: "browser_close",
451
+ description: "关闭浏览器(launch 模式下整个浏览器退出,profile 登录态保留;connect 模式只断开连接)。下次工具调用会自动重启。",
452
+ inputSchema: {
453
+ type: "object",
454
+ properties: {},
455
+ additionalProperties: false,
456
+ },
457
+ needsBrowser: false,
458
+ handler: async () => {
459
+ await manager.shutdown();
460
+ return text("✅ 浏览器已关闭。" + (manager.cfg.mode === "launch" ? `profile 已保留(${manager.cfg.profileDir}),下次启动登录态仍在。` : "外部浏览器未被关闭。"));
461
+ },
462
+ },
463
+ ];
464
+ // ---------- 注册到 Server ----------
465
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
466
+ tools: tools.map((t) => ({
467
+ name: t.name,
468
+ description: t.description,
469
+ inputSchema: t.inputSchema,
470
+ })),
471
+ }));
472
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
473
+ const name = request.params.name;
474
+ const def = tools.find((t) => t.name === name);
475
+ if (!def) {
476
+ return textError({ code: "unknown_tool", message: `未知工具: ${name}`, hint: "tools/list 查看可用工具" });
477
+ }
478
+ const args = (request.params.arguments ?? {});
479
+ try {
480
+ if (def.needsBrowser) {
481
+ const notes = await manager.ensureReady();
482
+ if (notes.length > 0 && notes.some((n) => n.includes("重启"))) {
483
+ // 重启提示在最前面
484
+ const result = await def.handler(args);
485
+ const first = result.content?.[0] ?? null;
486
+ if (first?.type === "text" && first.text) {
487
+ first.text = notes.join("\n") + "\n" + first.text;
488
+ }
489
+ return result;
490
+ }
491
+ }
492
+ return await def.handler(args);
493
+ }
494
+ catch (e) {
495
+ return textError(shapeError(e));
496
+ }
497
+ });
498
+ }
package/dist/util.js ADDED
@@ -0,0 +1,113 @@
1
+ // 通用工具:日志、超时、截断、id
2
+ import { appendFile, mkdir, stat, rename, readFile } from "node:fs/promises";
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ // ---------------- 日志 ----------------
6
+ const MAX_LOG_BYTES = 2 * 1024 * 1024; // 2MB 轮转
7
+ const KEEP_LOGS = 3;
8
+ let logDir = null;
9
+ let todayKey = "";
10
+ function dayKey() {
11
+ const d = new Date();
12
+ const p = (n) => String(n).padStart(2, "0");
13
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
14
+ }
15
+ async function rotateIfNeeded(file) {
16
+ try {
17
+ if (!existsSync(file))
18
+ return;
19
+ const s = await stat(file);
20
+ if (s.size < MAX_LOG_BYTES)
21
+ return;
22
+ for (let i = KEEP_LOGS - 1; i >= 1; i--) {
23
+ const from = `${file}.${i}`;
24
+ const to = `${file}.${i + 1}`;
25
+ if (existsSync(from))
26
+ await rename(from, to);
27
+ }
28
+ await rename(file, `${file}.1`);
29
+ }
30
+ catch {
31
+ /* 轮转失败不影响主流程 */
32
+ }
33
+ }
34
+ export async function initLogging(dir) {
35
+ logDir = dir;
36
+ await mkdir(dir, { recursive: true });
37
+ }
38
+ export async function log(level, msg, detail) {
39
+ const line = `[${new Date().toISOString()}] [${level}] ${msg}${detail !== undefined ? " | " + safeStringify(detail).slice(0, 2000) : ""}\n`;
40
+ if (process.env.BROWSER_MCP_DEBUG === "1") {
41
+ process.stderr.write(line);
42
+ }
43
+ if (!logDir)
44
+ return;
45
+ const key = dayKey();
46
+ if (key !== todayKey)
47
+ todayKey = key;
48
+ const file = path.join(logDir, `server-${key}.log`);
49
+ await rotateIfNeeded(file);
50
+ try {
51
+ await appendFile(file, line, "utf8");
52
+ }
53
+ catch {
54
+ /* 日志失败不影响主流程 */
55
+ }
56
+ }
57
+ export function safeStringify(v, max = 8000) {
58
+ const seen = new WeakSet();
59
+ try {
60
+ const s = JSON.stringify(v, (_k, val) => {
61
+ if (typeof val === "object" && val !== null) {
62
+ if (seen.has(val))
63
+ return "[Circular]";
64
+ seen.add(val);
65
+ }
66
+ if (typeof val === "string" && val.length > 500)
67
+ return val.slice(0, 500) + "…";
68
+ return val;
69
+ }, 2);
70
+ return s && s.length > max ? s.slice(0, max) + `…(截断,共${s.length}字符)` : s ?? String(v);
71
+ }
72
+ catch {
73
+ return String(v);
74
+ }
75
+ }
76
+ // ---------------- 超时竞速 ----------------
77
+ export class TimeoutError extends Error {
78
+ }
79
+ /** 给任意 Promise 加超时。Playwright 调用在浏览器进程死亡时可能永久悬挂,这是断联自愈的关键护栏。 */
80
+ export function withTimeout(p, ms, label) {
81
+ return new Promise((resolve, reject) => {
82
+ const timer = setTimeout(() => {
83
+ reject(new TimeoutError(`${label} 超过 ${ms}ms 未返回(浏览器可能已无响应)`));
84
+ }, ms);
85
+ p.then((v) => {
86
+ clearTimeout(timer);
87
+ resolve(v);
88
+ }, (e) => {
89
+ clearTimeout(timer);
90
+ reject(e);
91
+ });
92
+ });
93
+ }
94
+ // ---------------- 文本 ----------------
95
+ export function truncate(s, max, suffix = `…(截断,原长${s.length})`) {
96
+ if (s.length <= max)
97
+ return s;
98
+ return s.slice(0, max) + suffix;
99
+ }
100
+ export function uid() {
101
+ return Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
102
+ }
103
+ export async function readJsonFile(file) {
104
+ try {
105
+ if (!existsSync(file))
106
+ return null;
107
+ const raw = await readFile(file, "utf8");
108
+ return JSON.parse(raw);
109
+ }
110
+ catch {
111
+ return null;
112
+ }
113
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "browser-ref-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Reliable browser-control MCP server for AI agents: click by ref, self-healing sessions.",
5
+ "mcpName": "io.github.zy2755/browser-ref-mcp",
6
+ "type": "module",
7
+ "bin": {
8
+ "browser-ref-mcp": "dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "scripts": {
19
+ "build": "tsc",
20
+ "prepublishOnly": "npm run build",
21
+ "start": "node dist/index.js",
22
+ "serve:fixtures": "node test/serve.mjs",
23
+ "smoke": "node test/smoke.mjs"
24
+ },
25
+ "keywords": [
26
+ "mcp",
27
+ "mcp-server",
28
+ "model-context-protocol",
29
+ "browser-automation",
30
+ "browser-control",
31
+ "playwright",
32
+ "ai-agent",
33
+ "claude",
34
+ "cursor",
35
+ "web-scraping"
36
+ ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/zy2755/browser-ref-mcp.git"
40
+ },
41
+ "homepage": "https://github.com/zy2755/browser-ref-mcp#readme",
42
+ "bugs": {
43
+ "url": "https://github.com/zy2755/browser-ref-mcp/issues"
44
+ },
45
+ "author": "zy2755",
46
+ "license": "Apache-2.0",
47
+ "dependencies": {
48
+ "@modelcontextprotocol/sdk": "^1.12.0",
49
+ "playwright-core": "^1.53.0"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^24.0.0",
53
+ "typescript": "^5.8.0"
54
+ }
55
+ }