@nuwax-ai/nuwa-browser-mcp 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,216 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
204
+ Copyright 2026 Nuwax AI
205
+
206
+ Licensed under the Apache License, Version 2.0 (the "License");
207
+ you may not use this file except in compliance with the License.
208
+ You may obtain a copy of the License at
209
+
210
+ http://www.apache.org/licenses/LICENSE-2.0
211
+
212
+ Unless required by applicable law or agreed to in writing, software
213
+ distributed under the License is distributed on an "AS IS" BASIS,
214
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
215
+ See the License for the specific language governing permissions and
216
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # @nuwax-ai/nuwa-browser-mcp
2
+
3
+ 通过 MCP(Model Context Protocol)驱动 [nuwa-browser](https://github.com/dongdada29/nuwa-browser) —— 任何 MCP 客户端(Claude Desktop / Claude Code / ZCode / Cursor …)都能操控这个为 AI Agent 设计的浏览器:导航、语义快照、点击、输入、批量采集。
4
+
5
+ nuwa-browser 是一个 Chromium 浏览器:Agent 在隔离的 Space 里工作,复用你的登录态,但不打扰你自己的浏览。本包是它的 MCP Server(stdio),每次工具调用经 nuwa-browser CLI 跑一段 harness 脚本——与内置 Scheduler/Collect 同一条通路。
6
+
7
+ **版本与桌面应用对齐**:本包版本号 = nuwa-browser 应用版本号(同版本号 = 一起测过)。要求应用 ≥ v0.4.0(`nuwa_collect` 需多客户端 socket)。
8
+
9
+ ## 快速开始
10
+
11
+ 前置:已安装 nuwa-browser 桌面应用且正在运行(MCP 调用走它的 IPC socket),本机有 Node ≥ 22。
12
+
13
+ ```bash
14
+ # 1. 安装应用(macOS arm64 / Linux deb·rpm·AppImage;Windows 见仓库 README):
15
+ curl -fsSL https://s3.nuwax.com:9443/nuwax-packages/agent-engines/nuwa-browser/install-from-s3.sh | bash
16
+
17
+ # 2. 自检(CLI 发现、版本、应用 IPC 三连检查):
18
+ npx -y @nuwax-ai/nuwa-browser-mcp doctor
19
+ ```
20
+
21
+ 客户端配置(Claude Desktop `claude_desktop_config.json`,ZCode / Cursor / Claude Code 类似):
22
+
23
+ ```json
24
+ {
25
+ "mcpServers": {
26
+ "nuwa-browser": {
27
+ "command": "npx",
28
+ "args": ["-y", "@nuwax-ai/nuwa-browser-mcp"]
29
+ }
30
+ }
31
+ }
32
+ ```
33
+
34
+ 也可全局安装后直接用 bin:`npm i -g @nuwax-ai/nuwa-browser-mcp`,`command` 填 `nuwa-mcp`(别名 `nuwa-browser-mcp`)。
35
+
36
+ 环境变量:
37
+
38
+ - `NUWA_BROWSER_BIN` — `nuwa-browser` CLI 路径(默认 `~/.local/bin/nuwa-browser`,Windows 为 `nuwa-browser.cmd`;开发环境自动回退到仓库 checkout)
39
+ - `NUWA_MCP_TIMEOUT_MS` — 单次调用超时(默认 120000;`nuwa_collect` 固定 15 分钟)
40
+
41
+ ## 工具(10 个)
42
+
43
+ | 工具 | 作用 |
44
+ |---|---|
45
+ | `nuwa_navigate` | 打开/复用 tab 并等待加载 |
46
+ | `nuwa_snapshot` | 语义快照,带 `[ref=N, loc=...]` 标记(默认 12000 字符) |
47
+ | `nuwa_get_text` | 整页文本(默认 40000 字符),用于抽取/阅读 |
48
+ | `nuwa_click` | 按 selector 或 `@N` ref 点击 |
49
+ | `nuwa_type` | 填充输入框;可选回车 |
50
+ | `nuwa_press_key` | 页面级按键(Enter / Tab / …) |
51
+ | `nuwa_taskspaces_list` | 列出所有 Space(id/名称/所有权) |
52
+ | `nuwa_taskspace_use` | 按名创建/复用隔离 Space |
53
+ | `nuwa_collect` | 同一脚本并行跑 ≤16 个 URL(每 URL 一个隔离 Space) |
54
+ | `nuwa_site_tool` | 运行学到的站点工具(`site.runTool`) |
55
+
56
+ 动作工具接受可选 `taskSpace` 参数(默认 `"mcp"`)——专用隔离 Space,MCP 的操作不会碰用户自己的浏览,也不会触发「用户控制权硬停止」。相关调用传同一名字即可保持在同一 Space。
57
+
58
+ 典型循环:`nuwa_taskspace_use` → `nuwa_navigate` → `nuwa_snapshot` → `nuwa_click` / `nuwa_type` → `nuwa_snapshot`(验证)。
59
+
60
+ ## 排障
61
+
62
+ ```bash
63
+ npx -y @nuwax-ai/nuwa-browser-mcp doctor
64
+ ```
65
+
66
+ - **CLI not found** — 重跑安装脚本,或设 `NUWA_BROWSER_BIN` 指向 CLI。
67
+ - **cannot connect to app socket** — 桌面应用没在跑;启动后重试。
68
+ - **another CLI client is already connected** — 内置重试约 10 秒后仍忙才报错;通常等一下即恢复。
69
+
70
+ ## 并发说明
71
+
72
+ v0.4.0 起 IPC socket 支持多客户端(各自独立 Space);MCP server 内部仍会串行化自身调用,遇到忙 socket 自动退避重试(约 10 秒)。
73
+
74
+ ## 开发
75
+
76
+ ```bash
77
+ cd packages/mcp
78
+ pnpm test # build + 单元/集成测试(fake CLI,不需要真实应用)
79
+ ```
80
+
81
+ 架构:`src/tools.ts`(工具 → 脚本映射)→ `src/cli.ts`(串行 + spawn CLI + 忙重试 + Windows .cmd 处理)→ `src/index.ts`(MCP stdio server)。
82
+
83
+ ## License
84
+
85
+ Apache-2.0
package/dist/cli.js ADDED
@@ -0,0 +1,145 @@
1
+ /**
2
+ * cli.ts — run harness scripts through the nuwa-browser CLI.
3
+ *
4
+ * Every MCP tool call becomes one CLI invocation (script on stdin), the same
5
+ * one-shot pattern the Scheduler and Collect use. Calls are serialized
6
+ * in-process because the app's IPC socket accepts a single CLI client at a
7
+ * time; if the CLI reports the socket busy (typically a user's own session),
8
+ * we back off and retry before giving up.
9
+ */
10
+ import { spawn } from "node:child_process";
11
+ import { existsSync } from "node:fs";
12
+ import { join, dirname, resolve } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ const BUSY_RE = /another nuwa-browser CLI client is already connected|connection closed with \d+ pending request/i;
15
+ const DEFAULT_TIMEOUT_MS = 120 * 1000;
16
+ const BUSY_RETRY_MS = 10 * 1000;
17
+ const BUSY_BACKOFF_MS = 400;
18
+ /** Ascend from `start` toward the filesystem root, yielding <dir>/<rel>. */
19
+ function walkUpCandidates(start, rel) {
20
+ const out = [];
21
+ let dir = start;
22
+ for (let i = 0; i < 8 && dirname(dir) !== dir; i++) {
23
+ out.push(resolve(dir, rel));
24
+ dir = dirname(dir);
25
+ }
26
+ return out;
27
+ }
28
+ export function defaultCliPath() {
29
+ if (process.env.NUWA_BROWSER_BIN) {
30
+ return process.env.NUWA_BROWSER_BIN;
31
+ }
32
+ const isWin = process.platform === "win32";
33
+ const home = isWin ? process.env.USERPROFILE : process.env.HOME;
34
+ if (home) {
35
+ // The installers register the CLI here (bash shim on Unix, .cmd on Windows).
36
+ const local = join(home, ".local", "bin", isWin ? "nuwa-browser.cmd" : "nuwa-browser");
37
+ if (existsSync(local))
38
+ return local;
39
+ }
40
+ // Dev fallback: walk up from this compiled module to the repo checkout.
41
+ const names = isWin
42
+ ? [join("apps", "desktop", "cli", "nuwa-browser.cmd"), join("apps", "desktop", "cli", "nuwa-browser")]
43
+ : [join("apps", "desktop", "cli", "nuwa-browser")];
44
+ const here = dirname(fileURLToPath(import.meta.url));
45
+ for (const name of names) {
46
+ for (const c of walkUpCandidates(here, name)) {
47
+ if (existsSync(c))
48
+ return c;
49
+ }
50
+ }
51
+ throw new Error("nuwa-browser CLI not found — install the app (install-from-s3.sh) or set NUWA_BROWSER_BIN");
52
+ }
53
+ const CMD_SPECIAL_RE = /[\s"^&|<>()]/;
54
+ function quoteCmdArg(a) {
55
+ return a === "" || CMD_SPECIAL_RE.test(a) ? `"${a.replace(/"/g, '""')}"` : a;
56
+ }
57
+ /**
58
+ * Map a CLI path + args onto something Node can spawn. Node ≥20 refuses to
59
+ * exec `.cmd`/`.bat` files directly (CVE-2024-27980 hardening), so on Windows
60
+ * those route through cmd.exe: the whole command line is assembled and quoted
61
+ * here, and spawned with windowsVerbatimArguments so Node does not re-quote
62
+ * it. `/s` makes cmd strip exactly the outer quote pair we add below.
63
+ */
64
+ export function resolveSpawn(cliPath, cliArgs = [], platform = process.platform) {
65
+ if (platform === "win32" && /\.(cmd|bat)$/i.test(cliPath)) {
66
+ const commandLine = [cliPath, ...cliArgs].map(quoteCmdArg).join(" ");
67
+ return {
68
+ command: process.env.ComSpec || "cmd.exe",
69
+ args: ["/d", "/s", "/c", `"${commandLine}"`],
70
+ verbatimArgs: true,
71
+ };
72
+ }
73
+ return { command: cliPath, args: [...cliArgs], verbatimArgs: false };
74
+ }
75
+ function runOnce(cliPath, cliArgs, script, timeoutMs) {
76
+ return new Promise((resolveRun) => {
77
+ const chunks = [];
78
+ let timedOut = false;
79
+ let child;
80
+ const sp = resolveSpawn(cliPath, cliArgs);
81
+ try {
82
+ child = spawn(sp.command, sp.args, {
83
+ stdio: ["pipe", "pipe", "pipe"],
84
+ windowsVerbatimArguments: sp.verbatimArgs,
85
+ });
86
+ }
87
+ catch {
88
+ resolveRun({ code: -1, output: `spawn failed: ${cliPath}`, timedOut: false, busy: false });
89
+ return;
90
+ }
91
+ // If the CLI exits before reading stdin (bad flag, early crash) the stdin
92
+ // pipe breaks; swallow it instead of crashing the MCP server with EPIPE.
93
+ child.stdin?.on("error", () => { });
94
+ const timer = setTimeout(() => {
95
+ timedOut = true;
96
+ try {
97
+ child.kill("SIGKILL");
98
+ }
99
+ catch { }
100
+ }, timeoutMs);
101
+ if (typeof timer.unref === "function")
102
+ timer.unref();
103
+ child.stdout?.on("data", (d) => chunks.push(d));
104
+ child.stderr?.on("data", (d) => chunks.push(d));
105
+ child.on("error", (err) => {
106
+ clearTimeout(timer);
107
+ chunks.push(Buffer.from(String(err)));
108
+ finish();
109
+ });
110
+ child.on("close", (code) => {
111
+ clearTimeout(timer);
112
+ finish(code);
113
+ });
114
+ function finish(code = -1) {
115
+ let output = Buffer.concat(chunks).toString("utf8");
116
+ if (timedOut)
117
+ output += `\n(nuwa-mcp: timed out after ${timeoutMs}ms, killed)`;
118
+ resolveRun({ code, output, timedOut, busy: BUSY_RE.test(output) });
119
+ }
120
+ child.stdin?.write(script);
121
+ child.stdin?.end();
122
+ });
123
+ }
124
+ // Serialize every CLI run: the app's socket serves one client at a time.
125
+ let chain = Promise.resolve();
126
+ /** Run one harness script via the CLI; serial + busy-retrying. */
127
+ export function runCliScript(script, opts = {}) {
128
+ const attempt = async () => {
129
+ const cliPath = opts.cliPath ?? defaultCliPath();
130
+ const cliArgs = opts.cliArgs ?? [];
131
+ const timeoutMs = opts.timeoutMs ?? (Number(process.env.NUWA_MCP_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS);
132
+ const deadline = Date.now() + (opts.busyRetryMs ?? BUSY_RETRY_MS);
133
+ for (;;) {
134
+ const res = await runOnce(cliPath, cliArgs, script, timeoutMs);
135
+ if (!res.busy)
136
+ return res;
137
+ if (Date.now() + BUSY_BACKOFF_MS >= deadline)
138
+ return res;
139
+ await new Promise((r) => setTimeout(r, BUSY_BACKOFF_MS));
140
+ }
141
+ };
142
+ const next = chain.then(attempt, attempt);
143
+ chain = next.then(() => undefined, () => undefined);
144
+ return next;
145
+ }
package/dist/doctor.js ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * doctor.ts — `nuwa-mcp doctor`: preflight checks for support triage.
3
+ *
4
+ * Verifies the three links of the chain in order: CLI discovery, CLI exec
5
+ * (`-v`), and app IPC (a taskSpaces.list round-trip through the socket).
6
+ * Stops at the first failed link with a fix hint; exit code 0 = all green.
7
+ */
8
+ import { defaultCliPath, runCliScript } from "./cli.js";
9
+ import { TOOLS } from "./tools.js";
10
+ export async function doctor() {
11
+ let cliPath;
12
+ try {
13
+ cliPath = defaultCliPath();
14
+ }
15
+ catch (err) {
16
+ console.log(`[fail] nuwa-browser CLI not found: ${String(err)}`);
17
+ console.log(" fix: install the app (install-from-s3.sh) or set NUWA_BROWSER_BIN");
18
+ return 1;
19
+ }
20
+ console.log(`[ok] nuwa-browser CLI: ${cliPath}`);
21
+ const ver = await runCliScript("", { cliArgs: ["-v"], timeoutMs: 20_000 });
22
+ if (ver.code !== 0) {
23
+ const tail = ver.output.trim().split("\n").slice(-3).join("\n ");
24
+ console.log(`[fail] 'nuwa-browser -v' exited ${ver.code}: ${tail}`);
25
+ return 1;
26
+ }
27
+ console.log(`[ok] CLI version: ${ver.output.trim()}`);
28
+ const listTool = TOOLS.find((t) => t.name === "nuwa_taskspaces_list");
29
+ if (!listTool)
30
+ return 1;
31
+ const res = await runCliScript(listTool.build({}), { timeoutMs: 30_000 });
32
+ if (res.code !== 0) {
33
+ console.log(`[fail] app IPC check: ${res.output.trim() || `(exit=${res.code})`}`);
34
+ if (/cannot connect|socket|ECONNREFUSED|ENOENT/i.test(res.output)) {
35
+ console.log(" fix: start the nuwa-browser app and retry");
36
+ }
37
+ return 1;
38
+ }
39
+ let count = "?";
40
+ try {
41
+ const spaces = JSON.parse(res.output.trim());
42
+ if (Array.isArray(spaces))
43
+ count = String(spaces.length);
44
+ }
45
+ catch { }
46
+ console.log(`[ok] app IPC: ${count} task space(s) reachable`);
47
+ return 0;
48
+ }
package/dist/index.js ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * nuwa-mcp — MCP server exposing nuwa-browser over stdio.
4
+ *
5
+ * Any MCP client (Claude Desktop, ZCode, Cursor, …) can drive the agent
6
+ * browser: each tool call runs a harness script through the nuwa-browser
7
+ * CLI, the same one-shot path the Scheduler and Collect use. Requires the
8
+ * nuwa-browser app to be running (its IPC socket serves one CLI client at a
9
+ * time; calls are serialized here and retried if the socket is busy).
10
+ *
11
+ * Subcommands: `doctor` (preflight checks), `--help`/`-h`. Anything else
12
+ * (or no args) starts the MCP stdio server.
13
+ */
14
+ import { createRequire } from "node:module";
15
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
17
+ import { runCliScript, defaultCliPath } from "./cli.js";
18
+ import { doctor } from "./doctor.js";
19
+ import { TOOLS } from "./tools.js";
20
+ // Single source of truth: the version reported over MCP is this package's version.
21
+ const require_ = createRequire(import.meta.url);
22
+ const pkgVersion = require_("../package.json").version;
23
+ function startServer() {
24
+ const server = new McpServer({ name: "nuwa-browser", version: pkgVersion });
25
+ // Fail fast on startup if no CLI is discoverable — better a clear error now
26
+ // than an error on every tool call.
27
+ try {
28
+ defaultCliPath();
29
+ }
30
+ catch (err) {
31
+ console.error(String(err));
32
+ process.exit(1);
33
+ }
34
+ for (const tool of TOOLS) {
35
+ server.registerTool(tool.name, { description: tool.description, inputSchema: tool.schema }, async (args) => {
36
+ try {
37
+ const res = await runCliScript(tool.build(args), {
38
+ timeoutMs: tool.timeoutMs,
39
+ });
40
+ const text = res.output.trim() || `(no output; exit=${res.code})`;
41
+ return {
42
+ content: [{ type: "text", text }],
43
+ isError: res.code !== 0,
44
+ };
45
+ }
46
+ catch (err) {
47
+ return {
48
+ content: [{ type: "text", text: String(err) }],
49
+ isError: true,
50
+ };
51
+ }
52
+ });
53
+ }
54
+ async function run() {
55
+ const transport = new StdioServerTransport();
56
+ await server.connect(transport);
57
+ }
58
+ run().catch((err) => {
59
+ console.error(err);
60
+ process.exit(1);
61
+ });
62
+ }
63
+ const HELP = `nuwa-mcp ${pkgVersion} — MCP server exposing nuwa-browser over stdio.
64
+
65
+ Usage:
66
+ nuwa-mcp run the MCP stdio server (default; used by MCP clients)
67
+ nuwa-mcp doctor preflight checks: CLI discovery, 'cli -v', app IPC socket
68
+ nuwa-mcp --help show this help
69
+
70
+ Requires the nuwa-browser app to be running.
71
+
72
+ Environment:
73
+ NUWA_BROWSER_BIN path to the nuwa-browser CLI (default: ~/.local/bin, then repo checkout)
74
+ NUWA_MCP_TIMEOUT_MS per-call timeout in ms (default 120000; nuwa_collect uses 15 min)`;
75
+ const arg = process.argv[2];
76
+ if (arg === "doctor") {
77
+ doctor().then((code) => {
78
+ process.exitCode = code;
79
+ }, (err) => {
80
+ console.error(err);
81
+ process.exitCode = 1;
82
+ });
83
+ }
84
+ else if (arg === "--help" || arg === "-h") {
85
+ console.log(HELP);
86
+ }
87
+ else {
88
+ startServer();
89
+ }
package/dist/tools.js ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * tools.ts — MCP tool definitions: name, description, zod schema (raw shape),
3
+ * and the harness script each tool runs via the CLI. Every tool takes an
4
+ * optional `taskSpace`; when set, the script selects it first (each CLI run
5
+ * is a fresh process, so space selection does not persist across calls).
6
+ */
7
+ import { z } from "zod";
8
+ const taskSpace = z
9
+ .string()
10
+ .optional()
11
+ .describe("Task space to act in (default: 'mcp'); isolated from the user's own browsing");
12
+ // Action tools default to a dedicated space: acting without one targets the
13
+ // user-owned default space and correctly hard-stops, which is confusing for
14
+ // MCP clients. The default keeps MCP work isolated unless the caller opts in.
15
+ const DEFAULT_SPACE = "mcp";
16
+ function prelude(args) {
17
+ return `await taskSpaces.useOrCreate(${JSON.stringify(args.taskSpace ?? DEFAULT_SPACE)});\n`;
18
+ }
19
+ export const TOOLS = [
20
+ {
21
+ name: "nuwa_navigate",
22
+ description: "Open (or reuse) a tab at a URL in nuwa-browser and wait for it to load. Returns tab info.",
23
+ schema: {
24
+ url: z.string().describe("Absolute URL to open"),
25
+ timeoutSec: z.number().optional().describe("Navigation timeout in seconds (default 30)"),
26
+ taskSpace,
27
+ },
28
+ build: (a) => prelude(a) +
29
+ `const info = await browser.openOrReuseTab(${JSON.stringify(a.url)}, { wait: true, timeout: ${Number(a.timeoutSec) || 30} });\n` +
30
+ `console.log(JSON.stringify(info));`,
31
+ },
32
+ {
33
+ name: "nuwa_snapshot",
34
+ description: "Semantic snapshot of the current page (accessibility-ish tree with [ref=N, loc=...] markers). This is the primary way to see page content for follow-up clicks.",
35
+ schema: {
36
+ scope: z.enum(["full_page", "only_within_viewport"]).optional(),
37
+ maxChars: z.number().optional().describe("Truncate output (default 12000)"),
38
+ taskSpace,
39
+ },
40
+ build: (a) => prelude(a) +
41
+ `const snap = await page.snapshot(${a.scope ? `{ scope: ${JSON.stringify(a.scope)} }` : ""});\n` +
42
+ `console.log(snap.slice(0, ${Number(a.maxChars) || 12000}));`,
43
+ },
44
+ {
45
+ name: "nuwa_get_text",
46
+ description: "Full text snapshot of the current page — same as nuwa_snapshot with a larger default cap, for extraction/reading.",
47
+ schema: {
48
+ maxChars: z.number().optional().describe("Truncate output (default 40000)"),
49
+ taskSpace,
50
+ },
51
+ build: (a) => prelude(a) +
52
+ `const snap = await page.snapshot();\n` +
53
+ `console.log(snap.slice(0, ${Number(a.maxChars) || 40000}));`,
54
+ },
55
+ {
56
+ name: "nuwa_click",
57
+ description: "Click an element by selector or @N ref from a previous snapshot. Take a snapshot first if you don't have a target.",
58
+ schema: {
59
+ target: z.string().describe("CSS/XPath selector, loc=... locator, or @N ref"),
60
+ label: z.string().optional().describe("Human-readable action label (visual feedback)"),
61
+ taskSpace,
62
+ },
63
+ build: (a) => prelude(a) +
64
+ `await page.locator(${JSON.stringify(a.target)}).click(${a.label ? `{ label: ${JSON.stringify(a.label)} }` : ""});\n` +
65
+ `console.log('clicked ' + ${JSON.stringify(a.target)});`,
66
+ },
67
+ {
68
+ name: "nuwa_type",
69
+ description: "Fill an input with text (replaces existing content). Optionally press Enter after.",
70
+ schema: {
71
+ target: z.string().describe("CSS/XPath selector, loc=... locator, or @N ref"),
72
+ text: z.string().describe("Text to type"),
73
+ pressEnter: z.boolean().optional().describe("Press Enter after filling (default false)"),
74
+ taskSpace,
75
+ },
76
+ build: (a) => prelude(a) +
77
+ `await page.locator(${JSON.stringify(a.target)}).fill(${JSON.stringify(a.text)});\n` +
78
+ (a.pressEnter
79
+ ? `await page.locator(${JSON.stringify(a.target)}).press('Enter');\n`
80
+ : "") +
81
+ `console.log('typed into ' + ${JSON.stringify(a.target)});`,
82
+ },
83
+ {
84
+ name: "nuwa_press_key",
85
+ description: "Press a keyboard key at the page level (e.g. 'Enter', 'Tab', 'ArrowDown', 'Escape').",
86
+ schema: {
87
+ key: z.string().describe("Key name, e.g. 'Enter', 'Tab'"),
88
+ taskSpace,
89
+ },
90
+ build: (a) => prelude(a) +
91
+ `await page.keyboard.press(${JSON.stringify(a.key)});\n` +
92
+ `console.log('pressed ' + ${JSON.stringify(a.key)});`,
93
+ },
94
+ {
95
+ name: "nuwa_taskspaces_list",
96
+ description: "List all task spaces (id, name, ownership, recent tabs).",
97
+ schema: {},
98
+ build: () => `console.log(JSON.stringify(await taskSpaces.list()));`,
99
+ },
100
+ {
101
+ name: "nuwa_taskspace_use",
102
+ description: "Create or reuse an isolated task space by name; subsequent calls with the same taskSpace run inside it.",
103
+ schema: {
104
+ name: z.string().describe("Space name, e.g. 'research-xiaohongshu'"),
105
+ },
106
+ build: (a) => `console.log(JSON.stringify(await taskSpaces.useOrCreate(${JSON.stringify(a.name)})));`,
107
+ },
108
+ {
109
+ name: "nuwa_collect",
110
+ description: "Run the same script across many URLs in parallel (one isolated space per URL, ≤16). The script sees COLLECT_URL / COLLECT_INDEX. Returns per-URL status and output.",
111
+ schema: {
112
+ task: z.string().describe("Task name; spaces are named <task>#<i>"),
113
+ urls: z.array(z.string()).describe("URLs to process (max 16)"),
114
+ script: z.string().describe("Heredoc body run once per URL (COLLECT_URL/COLLECT_INDEX predefined)"),
115
+ concurrency: z.number().optional().describe("Parallel runners (1-8, default 3)"),
116
+ timeoutMs: z.number().optional().describe("Per-URL timeout in ms (default 10 min)"),
117
+ },
118
+ timeoutMs: 15 * 60 * 1000,
119
+ build: (a) => `const r = await globalThis.ego.collect(${JSON.stringify({
120
+ task: a.task,
121
+ urls: a.urls,
122
+ script: a.script,
123
+ ...(a.concurrency ? { concurrency: a.concurrency } : {}),
124
+ ...(a.timeoutMs ? { timeoutMs: a.timeoutMs } : {}),
125
+ })});\n` +
126
+ `for (const item of r.results) item.output = String(item.output ?? '').slice(0, 4000);\n` +
127
+ `console.log(JSON.stringify(r));`,
128
+ },
129
+ {
130
+ name: "nuwa_site_tool",
131
+ description: "Run a learned site tool (see site skills / learnings). Use site.skillsForUrl to discover tools for a URL first.",
132
+ schema: {
133
+ siteId: z.string().describe("Learning id, e.g. 'x-com'"),
134
+ tool: z.string().describe("Tool name from the manifest"),
135
+ args: z.record(z.any()).optional().describe("Tool arguments"),
136
+ taskSpace,
137
+ },
138
+ build: (a) => prelude(a) +
139
+ `console.log(JSON.stringify(await site.runTool(${JSON.stringify(a.siteId)}, ${JSON.stringify(a.tool)}, ${JSON.stringify(a.args ?? {})})));`,
140
+ },
141
+ ];
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@nuwax-ai/nuwa-browser-mcp",
3
+ "version": "0.5.3",
4
+ "description": "MCP server exposing nuwa-browser — any MCP client can drive the agent browser (navigate, snapshot, click, type, collect).",
5
+ "type": "module",
6
+ "bin": {
7
+ "nuwa-mcp": "dist/index.js",
8
+ "nuwa-browser-mcp": "dist/index.js"
9
+ },
10
+ "main": "dist/index.js",
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "engines": {
15
+ "node": ">=22"
16
+ },
17
+ "license": "Apache-2.0",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/dongdada29/nuwa-browser.git",
21
+ "directory": "packages/mcp"
22
+ },
23
+ "homepage": "https://github.com/dongdada29/nuwa-browser#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/dongdada29/nuwa-browser/issues"
26
+ },
27
+ "keywords": [
28
+ "mcp",
29
+ "mcp-server",
30
+ "browser",
31
+ "ai-agent",
32
+ "chromium",
33
+ "browser-automation",
34
+ "nuwa"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "@modelcontextprotocol/sdk": "^1.18.0",
41
+ "zod": "^3.25.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^22.15.29",
45
+ "typescript": "^5.8.3"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.json && chmod +x dist/index.js",
49
+ "test": "pnpm run build && node --test \"src/**/*.test.mjs\""
50
+ }
51
+ }