jtcrpa-mcp 0.4.1 → 0.6.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/README.md CHANGED
@@ -1,207 +1,111 @@
1
- # 九头虫 MCP 桥接器 · Jiutouchong MCP Bridge
1
+ # 九头虫 RPA MCP 桥接器 · Jiutouchong RPA MCP Bridge
2
2
 
3
3
  [简体中文](#简体中文) · [English](#english)
4
4
 
5
5
  ## 简体中文
6
6
 
7
- `jtcrpa-mcp` 让 MCP 客户端连接这台 Windows 电脑上的九头虫浏览器扩展。连接后,你可以让 AI 查看指定浏览器的标签页、创建和运行工作流、检查日志,或读取采集到的数据。
7
+ `jtcrpa-mcp` 把外部 AI 客户端接到你浏览器里的**九头虫 Agent**。下面用 Codex 做一次完整采集。你会在聊天里拿到书店首页 4 本书的书名和价格,还能把同一条规则用到下一页。[九头虫 RPA 官网与扩展下载](https://jtcrpa.com/) · [九头虫 Agent 使用手册](https://doc.jtcrpa.com/)
8
8
 
9
- ### 安装并连接第一个浏览器
9
+ ### 首次连接
10
10
 
11
- 1. 准备原生 Windows、Windows PowerShell 5.1、Node.js **20.19.0 或更高版本**,以及装有九头虫扩展的 Chrome 或 Firefox 配置。使用 Codex 的用户还需要能在终端运行 `codex`。在 PowerShell 中安装桥接器并检查版本。
11
+ 1. **浏览器里找到 MCP 入口。** 在 macOS 或 Windows 上将**九头虫 Agent** 添加到 Chrome 或 Firefox。点击浏览器工具栏的九头虫图标打开侧边栏,再点底部的 **设置菜单 ☰ → MCP 连接**。打开页面后应能看到 **开启 MCP 连接** 开关。[设置菜单截图](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/images/settings-menu-zh.png) · [扩展安装说明](https://doc.jtcrpa.com/guide/install.html)
12
12
 
13
- ```powershell
14
- npm.cmd install --global jtcrpa-mcp
15
- jtcrpa-mcp.cmd --version
16
- ```
17
-
18
- 2. 在要连接的浏览器中打开九头虫的**设置 → MCP 连接**。复制**注册当前浏览器**下的整条命令,在 PowerShell 中运行。页面会填好当前扩展 ID,Chrome 使用 `add --chrome-id`,Firefox 使用 `add --firefox-id`。首次运行会为当前 Windows 用户注册本机宿主。
19
- 3. 在同一页面打开**开启 MCP 连接**,按浏览器提示允许本机通信。状态变为**浏览器与本机程序已连接**后,在**接入外部 AI**中选择客户端。
13
+ 如果菜单里没有这个入口,先确认扩展版本。Chrome 和 Firefox 商店发布的 `2.0.2` 都缺少 MCP。只有商店版时,可向九头虫咨询支持 MCP 的安装包。[联系九头虫](https://jtcrpa.com/contact)
20
14
 
21
- | 客户端 | 在哪里使用页面生成的命令或配置 |
22
- | --- | --- |
23
- | Codex | 在 PowerShell 中执行页面给出的 `codex mcp add` 完整命令。它会保存名为 `jtcrpa` 的服务。重新连接 MCP 或重启 Codex。 |
24
- | Claude Code | 在 PowerShell 中执行页面给出的 `config` 命令,将输出的 `mcpServers.jtcrpa` 合并到项目的 `.mcp.json`。重启客户端,在 `/mcp` 查看。 |
25
- | DeepSeek Harness | 在 PowerShell 中执行页面给出的 `config` 命令,把输出的插件条目加入 Harness 的插件列表,然后重启客户端。 |
15
+ 2. **在终端安装桥接器。** 需要 Node.js 20.19.0 或更高版本。macOS 打开「终端」,Windows 打开 PowerShell 5.1。已发布的兼容版本可用下面的命令安装。[Node.js 下载](https://nodejs.org/en/download)
26
16
 
27
- 4. 在客户端发送 **“检查九头虫 MCP 连接,并列出当前浏览器标签页。”** 对照浏览器中打开的标签页即可确认连到了正确的配置。Codex 已在 Chrome 和 Firefox 上完成端到端验收。Claude Code 和 DeepSeek Harness 提供配置生成,尚未完成同等的端到端验收。
17
+ ```sh
18
+ node --version
19
+ npm install -g jtcrpa-mcp
20
+ jtcrpa-mcp --version
21
+ ```
28
22
 
29
- 安装、注册和客户端接入通常只做一次。保持该浏览器配置的 MCP 开关开启,浏览器会按需启动本机宿主。日常使用时打开目标浏览器即可。
23
+ 此 Codex CLI 流程需要支持浏览器实例绑定的扩展和 0.5.1 或更高版本的桥接器。开发测试可在本仓库运行 `npm run build` 后使用 `npm pack` 生成的本地安装包。
30
24
 
31
- ### 使用工作流和数据集
25
+ 3. **连接你要用的浏览器。** 在该浏览器的 **MCP 连接** 页面打开 **开启 MCP 连接** 开关,按提示允许本机通信,然后选择 **Codex** 查看首次接入命令。
26
+ 4. **登记 MCP 服务。** 将页面给出的整条命令粘贴到终端运行。命令核对目标浏览器后,显示浏览器名称和 MCP 服务名,然后退出。Codex 加载这项配置后,你可以在自己的对话里提出任务。首次访问后,扩展会显示访问时间。要使用另一份浏览器配置,从那份配置的扩展页接入。[安装 Codex CLI](https://developers.openai.com/codex/cli/) · [使用 Claude Code 或 DeepSeek Harness](docs/usage.md#客户端配置)
32
27
 
33
- | 用途 | MCP 工具 | 示例 |
34
- | --- | --- | --- |
35
- | 确认连接、读取页面 | `connection_status`、`connection_ping`、`browser_context`、`page_probe` | “列出当前标签页,查看所选商品列表页能提取哪些字段。” |
36
- | 查找或编排工作流 | `workflow_list`、`workflow_get`、`workflow_contract`、`workflow_save` | “把当前页面的商品名称和价格采集规则保存为工作流。” |
37
- | 执行并检查结果 | `workflow_run`、`run_get`、`run_control` | “在当前列表页运行刚才的工作流,再告诉我状态和最近日志。” |
38
- | 读取采集数据 | `dataset_list`、`dataset_read` | “找到商品数据集,读取前 20 行,只返回商品名称和价格。” |
28
+ ### 第一次用 MCP 采集书名和价格
39
29
 
40
- 保存新工作流或修改已有工作流后,客户端应等你确认再执行。启动返回 `runId`,用 `run_get` 查询完成状态。写操作超时后,先用原 UUID 请求编号查询 `connection_status`,再核对最近运行。暂停可能仍有在途动作,结束运行不会撤销已执行的操作。
30
+ **① 读取网页。** 在已接入九头虫 MCP 的 AI 对话中发送下面的任务。九头虫会在已绑定的浏览器中打开或复用目标页,沿用该浏览器的登录状态。如果书店显示英文,可在页头切到 **简体中文**。
41
31
 
42
- `dataset_read` 按 `datasetId` 或 `datasetName` 精确读取,两者任选其一。页码从 1 开始,默认每页 50 行、最多 200 行,`fields` 可指定字段。采集仍在进行时,翻页读到的是当时的数据。单次结果上限为 256 KiB,超限时请减小页大小或减少字段。
32
+ > 用九头虫打开 https://doc.jtcrpa.com/practice/index.html ,告诉我页面标题和第一本书的书名、价格。
43
33
 
44
- ### 管理多个浏览器配置
34
+ 练习场首页的第一本书是《山海之间》,价格 ¥32.00。
45
35
 
46
- 直接使用扩展页面生成的接入命令时,客户端绑定该浏览器配置的实例 UUID。需要同时接入多个配置时,为每个实例设置不同的 MCP 服务名。要通过登记编号管理连接,可在 PowerShell 运行以下命令。
36
+ **② 保存一条可复用的规则。** 在同一个聊天里发送第二条消息。
47
37
 
48
- ```powershell
49
- jtcrpa-mcp.cmd list
50
- jtcrpa-mcp.cmd list --json
51
- ```
38
+ > 把书店当前列表页的每本书采成一行,书名列叫 title,价格列叫 price,保留货币符号,只采当前页。先在页面上试采,再把规则保存为工作流「Bookshop demo」,运行时写入数据集 bookshop_demo。告诉我保存的工作流编号,等我确认再运行。
52
39
 
53
- 如果列表显示「待选择实例」,确认目标浏览器已开启 MCP,然后执行列表给出的 `add ... --instance ...` 命令。相同扩展 ID 的多个浏览器配置可以分别选择。选定后,用实际编号替换下面示例中的 `c1`。
40
+ 此时你应拿到 `workflowId`(工作流编号)。也可以在扩展的 **主工作台** 搜索 `Bookshop demo` 查看已保存的规则。页面会保留,方便检查或试运行。需要关页时,可以自己关闭,也可以在对话里明确指定要关闭的页面。
54
41
 
55
- ```powershell
56
- jtcrpa-mcp.cmd config --connection c1 --client codex
57
- ```
42
+ **③ 运行并核对数据。** 收到保存结果后,再单独发第三条消息。
58
43
 
59
- 可选客户端为 `codex`、`claude`、`deepseek`,省略 `--client` 会输出三种配置。生成的启动参数包含登记的绑定 UUID。更换已选实例或扩展时,先添加新连接、更新客户端配置,再运行 `jtcrpa-mcp.cmd remove` 选择旧登记并确认。脚本可用 `jtcrpa-mcp.cmd remove c1` 直接删除指定登记。删除后,即使显示编号被复用,旧配置也会返回 `CONNECTION_REMOVED`。
44
+ > 确认,现在在刚才的书店首页运行 Bookshop demo。等运行结束,告诉我本次写了几行,再从 bookshop_demo 读出 title 和 price,用表格显示。
60
45
 
61
- ### 排查连接问题
46
+ 首次在空数据集中运行,本次应写入 **4 行**。也可以在扩展的 **数据存储** 找到 `bookshop_demo`,点 **预览**,对照同一份结果。
62
47
 
63
- | 现象 | 处理 |
48
+ | title | price |
64
49
  | --- | --- |
65
- | PowerShell 提示禁止运行脚本,或找不到命令 | 使用上面的 `npm.cmd` 和 `jtcrpa-mcp.cmd`。用 `npm.cmd prefix --global` 查看 Windows 全局命令目录,并确认它在当前终端的 `PATH` 中。 |
66
- | npm 镜像提示找不到刚发布的包 | 直接从官方源安装,运行 `npm.cmd install --global jtcrpa-mcp --registry=https://registry.npmjs.org`。 |
67
- | `Access to the specified native messaging host is forbidden` | 从当前扩展的 MCP 页面重新复制注册命令,对照 `list` 的完整扩展 ID,运行命令后重新开启 MCP。开发版扩展换 ID 后也要登记新 ID。 |
68
- | 「本机通信接口尚未就绪」或提示需要权限 | 在浏览器扩展管理页重新加载九头虫,返回 MCP 页面开启连接,按提示允许本机通信。 |
69
- | `BROWSER_OFFLINE` 或标签页属于另一个浏览器 | 打开目标浏览器配置并开启 MCP,核对页面的实例 UUID 与客户端配置。复制浏览器配置造成实例冲突时,使用扩展页面的「生成新实例 ID」并更新该客户端配置。 |
70
- | `CONNECTION_INSTANCE_NOT_SELECTED` 或 `CONNECTION_REMOVED` | 前者按 `list` 的提示选择实例。后者从现有登记重新生成客户端配置。 |
71
-
72
- ### 升级和卸载
73
-
74
- 在原位置升级时,关闭 MCP 连接,运行 `npm.cmd install --global jtcrpa-mcp@latest`,再开启连接。移动 npm 全局目录或 Node.js 后,重跑当前扩展的注册命令。使用绝对路径的客户端配置也要重新生成。
75
-
76
- 卸载前先关闭所有浏览器配置的 MCP 开关,再依次运行以下命令。第一条清理本安装的宿主登记和连接,第二条移除 npm 全局包。
50
+ | 山海之间 | ¥32.00 |
51
+ | 城市慢行 | ¥45.00 |
52
+ | 生活的留白 | ¥39.00 |
53
+ | 月光落在书页上 | ¥28.50 |
77
54
 
78
- ```powershell
79
- jtcrpa-mcp.cmd uninstall
80
- npm.cmd uninstall --global jtcrpa-mcp
81
- ```
55
+ **下次复用。** 点击书店的 **下一页**,在聊天中说「找到已保存的 Bookshop demo,在书店第 2 页运行,告诉我这次写入几行」。这次应再写入 4 行,其中有《旅途中的小地图》¥48.00。以后打开同一浏览器配置并保持 MCP 开启即可,浏览器和客户端会按需启动桥接器。
82
56
 
83
- ### 开发和验证
84
-
85
- 在独立桥接器仓库的根目录运行以下命令。`npm test` 和 `npm pack` 都会编译 TypeScript,用户安装的是编译后的 JavaScript。与扩展的端到端验收方法见下方的「[维护者参考](#维护者参考)」。
86
-
87
- ```powershell
88
- npm.cmd ci
89
- npm.cmd run check
90
- npm.cmd test
91
- npm.cmd pack
92
- ```
57
+ [MCP 工具的实际参数和调用顺序](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/usage.md#书店示例的工具调用) · [连接或采集遇到问题](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/usage.md#排查连接问题) · [开发与发布](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/publishing.md#简体中文)
93
58
 
94
59
  ## English
95
60
 
96
- `jtcrpa-mcp` connects an MCP client to the Jiutouchong browser extension on your Windows computer. Use it to inspect tabs in a chosen browser profile, create and run workflows, check run logs, or read collected data.
61
+ `jtcrpa-mcp` connects an external AI client to **Jiutouchong Agent** in your browser. In this walkthrough, you’ll use Codex chat to collect the four titles and prices on a bookshop page, check the saved rows and run the same workflow on the next page. [Jiutouchong RPA website and extension downloads](https://jtcrpa.com/en) · [Jiutouchong Agent user manual](https://doc.jtcrpa.com/en/)
97
62
 
98
- ### Connect your first browser
63
+ ### First-time setup
99
64
 
100
- 1. Use native Windows with Windows PowerShell 5.1, **Node.js 20.19.0 or later**, and the Jiutouchong extension installed in a Chrome or Firefox profile. For Codex, the `codex` command must also be available in your terminal. Install the bridge and check its version in PowerShell.
65
+ 1. **Find MCP in the browser.** On macOS or Windows, add **Jiutouchong Agent** to Chrome or Firefox. Click its toolbar icon to open the sidebar, then choose **Settings ☰ → MCP connection** at the bottom. Look for the **Enable MCP connection** switch. [See the Settings menu](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/images/settings-menu-en.png) · [Extension installation guide](https://doc.jtcrpa.com/en/guide/install.html)
101
66
 
102
- ```powershell
103
- npm.cmd install --global jtcrpa-mcp
104
- jtcrpa-mcp.cmd --version
105
- ```
67
+ If the menu entry is missing, check the extension build. Version `2.0.2` from both browser stores lacks MCP. If you only have the store release, contact Jiutouchong about an MCP-enabled build. [Contact Jiutouchong](https://jtcrpa.com/en/contact)
106
68
 
107
- 2. In the browser profile you want to use, open the extension’s **Settings → MCP connection**. Copy the entire command under **Register this browser** and run it in PowerShell. The extension fills in its own ID. Chrome uses `add --chrome-id` and Firefox uses `add --firefox-id`. The first registration installs the native host for the current Windows user.
108
- 3. Turn on **Enable MCP connection** on that page and grant native messaging permission when prompted. Once the page shows **Browser connected to the local program**, choose your client under **Connect an AI app**.
69
+ 2. **Install the bridge in a terminal.** Use Node.js 20.19.0 or later. Open Terminal on macOS or PowerShell 5.1 on Windows. For a published version supporting your platform, run the following commands. [Download Node.js](https://nodejs.org/en/download)
109
70
 
110
- | Client | How to use the command or configuration from the extension |
111
- | --- | --- |
112
- | Codex | Run the full `codex mcp add` command in PowerShell. It saves a service named `jtcrpa`. Reconnect the MCP client or restart Codex. |
113
- | Claude Code | Run the generated `config` command in PowerShell. Merge the resulting `mcpServers.jtcrpa` entry into the project’s `.mcp.json`, restart Claude Code and check `/mcp`. |
114
- | DeepSeek Harness | Run the generated `config` command in PowerShell, add the resulting plugin entry to the Harness plugin list and restart the client. |
115
-
116
- 4. Ask your client **“Check the Jiutouchong MCP connection and list the tabs in the connected browser.”** Match the returned tabs to the ones open in your target profile. Codex has been tested end to end with both Chrome and Firefox. Configuration generation is available for Claude Code and DeepSeek Harness. An equivalent end-to-end test for these two clients is pending.
71
+ ```sh
72
+ node --version
73
+ npm install -g jtcrpa-mcp
74
+ jtcrpa-mcp --version
75
+ ```
117
76
 
118
- Setup is normally a one-time operation. Leave MCP enabled in the target profile. The browser starts the native host on demand when you open that profile.
77
+ This Codex CLI flow requires an extension that supports browser instance binding and bridge version 0.5.1 or later. To test a development checkout, run `npm run build` and install the local package produced by `npm pack`.
119
78
 
120
- ### Work with workflows and datasets
79
+ 3. **Connect the browser you want to use.** In that profile, open **MCP connection**, turn on the connection switch and allow native messaging when prompted. Select **Codex** to see the first-time setup command.
80
+ 4. **Register the MCP server.** Run the setup command in your terminal. It verifies the target browser, prints its display name and MCP server name, then exits. Once Codex has loaded the configuration, enter your task in your own conversation. The extension shows the time of the first access. To use another profile, start from its extension page. [Install the Codex CLI](https://developers.openai.com/codex/cli/) · [Use Claude Code or DeepSeek Harness](docs/usage.md#client-configuration)
121
81
 
122
- | Task | MCP tools | Example request |
123
- | --- | --- | --- |
124
- | Check the connection and inspect a page | `connection_status`, `connection_ping`, `browser_context`, `page_probe` | “List the tabs and check which fields can be extracted from the selected product listing.” |
125
- | Find or create a workflow | `workflow_list`, `workflow_get`, `workflow_contract`, `workflow_save` | “Save a workflow that collects product names and prices from this page.” |
126
- | Run a workflow and check the result | `workflow_run`, `run_get`, `run_control` | “Run that saved workflow on this listing and show its status and recent logs.” |
127
- | Read collected data | `dataset_list`, `dataset_read` | “Find the product dataset and show the first 20 rows with just names and prices.” |
82
+ ### Collect your first four books
128
83
 
129
- After saving a new or edited workflow, the client should wait for your confirmation before running it. Starting a workflow returns a `runId`. Use `run_get` to check whether it finished. If a write times out, query `connection_status` with the original request UUID and check recent runs before retrying. An action already in progress can finish after a pause. Stopping a run does not undo actions it has already taken.
84
+ **① Read a page.** Send this task in an AI conversation connected to Jiutouchong MCP. The tool opens or reuses the page in the bound browser profile, using that profile’s sign-in state. If the bookshop appears in Chinese, select **English** in the page header.
130
85
 
131
- For `dataset_read`, supply exactly one of `datasetId` and `datasetName`. Pages start at 1, with 50 rows by default and a maximum of 200. Use `fields` to select columns. Pages reflect live data if collection is still running. If a result exceeds 256 KiB, request fewer rows or columns.
86
+ > Use Jiutouchong to open https://doc.jtcrpa.com/en/practice/index.html and tell me the page title and the first book’s title and price.
132
87
 
133
- ### Manage multiple browser profiles
88
+ The first book on the practice homepage is *Between Mountains and Seas* at ¥32.00.
134
89
 
135
- The setup command from the extension binds the client to the instance UUID of that browser profile. Give each instance its own MCP service name when connecting several profiles. To manage connections by their registration number, run the following in PowerShell.
90
+ **② Save a reusable workflow.** Send this in the same chat.
136
91
 
137
- ```powershell
138
- jtcrpa-mcp.cmd list
139
- jtcrpa-mcp.cmd list --json
140
- ```
92
+ > Collect one row per book on the current listing page. Name the columns title and price and keep the currency symbol. Preview the extraction on the page, then save a workflow named “Bookshop demo” that writes to the bookshop_demo dataset when run. Give me the saved workflow ID and wait for my confirmation.
141
93
 
142
- If the list shows `待选择实例` (select an instance), enable MCP in the intended profile and run the `add ... --instance ...` command shown in the list. Profiles with the same extension ID can be selected separately. After selecting a target, substitute its connection number for `c1` in this example.
94
+ You should receive a `workflowId`. To find the saved rule in the extension, open **Workbench** and search for `Bookshop demo`. The tab stays open for review or a trial run. Close it yourself or explicitly ask the assistant to close that specific page.
143
95
 
144
- ```powershell
145
- jtcrpa-mcp.cmd config --connection c1 --client codex
146
- ```
96
+ **③ Run it and check the saved rows.** Once the client reports that it saved the workflow, send a separate message.
147
97
 
148
- The supported client identifiers are `codex`, `claude` and `deepseek`. Omit `--client` to print all three configurations. The generated startup arguments contain the registration’s binding UUID. To switch to a different extension ID or selected instance, add the new connection, update the client, then run `jtcrpa-mcp.cmd remove` to select and confirm the old registration. In scripts, `jtcrpa-mcp.cmd remove c1` removes the specified entry directly. The old client configuration returns `CONNECTION_REMOVED` even if its display number is later reused.
98
+ > Yes, run Bookshop demo on the bookshop homepage now. Wait for it to finish, tell me how many rows this run saved, then read title and price from bookshop_demo and show them as a table.
149
99
 
150
- ### Troubleshooting
100
+ On the first run with an empty dataset, expect **four rows**. You can also open **Storage** in the extension, find `bookshop_demo` and click **Preview** to see the same records.
151
101
 
152
- | Symptom | What to do |
102
+ | title | price |
153
103
  | --- | --- |
154
- | PowerShell reports that scripts are disabled, or cannot find the command | Use `npm.cmd` and `jtcrpa-mcp.cmd` as shown above. Check the Windows global command directory with `npm.cmd prefix --global` and ensure it is on the current terminal’s `PATH`. |
155
- | An npm mirror cannot find a newly published version | Install from the public registry with `npm.cmd install --global jtcrpa-mcp --registry=https://registry.npmjs.org`. |
156
- | `Access to the specified native messaging host is forbidden` | Copy the registration command from the current extension, check its complete ID against `list`, run the command and turn MCP on again. Register the new ID if a development build’s extension ID has changed. |
157
- | The native messaging interface is unavailable, or the browser requests permission | Reload Jiutouchong from the browser’s extensions page, enable the connection again and allow native messaging when prompted. |
158
- | `BROWSER_OFFLINE` or tabs from the wrong browser | Open the target profile, enable MCP and compare its instance UUID with the client configuration. If a copied profile produces an instance conflict, use the extension’s option to generate a new instance ID and update that client. |
159
- | `CONNECTION_INSTANCE_NOT_SELECTED` or `CONNECTION_REMOVED` | For the first error, select a target using the instruction from `list`. For the second, generate a fresh client configuration from an existing registration. |
160
-
161
- ### Upgrade or uninstall
162
-
163
- For an in-place upgrade, turn MCP off, run `npm.cmd install --global jtcrpa-mcp@latest` and reconnect. If Node.js or the npm global directory moves, rerun the registration command from the extension. Regenerate client configurations that refer to the previous absolute paths.
164
-
165
- To uninstall, first disable MCP in all connected browser profiles. The first command below removes this installation’s native host registrations and connections. The second removes the global npm package.
166
-
167
- ```powershell
168
- jtcrpa-mcp.cmd uninstall
169
- npm.cmd uninstall --global jtcrpa-mcp
170
- ```
171
-
172
- ### Development and verification
173
-
174
- Run these commands in the root of the standalone bridge repository. Both `npm test` and `npm pack` compile TypeScript. The npm package ships the compiled JavaScript. For extension integration tests, see the [maintainer reference](#maintainer-reference).
175
-
176
- ```powershell
177
- npm.cmd ci
178
- npm.cmd run check
179
- npm.cmd test
180
- npm.cmd pack
181
- ```
182
-
183
- ## 维护者参考
184
-
185
- - `bin/cli.mjs` 按命令加载 `dist/`。`src/mcp.ts` 装配 `src/tools/` 的连接、编排、执行和数据工具,后者由 `forwarded.ts` 转发到扩展。工具说明为中文,工具名、参数名和状态标识在两种语言中一致。
186
- - 浏览器通过 Native Messaging 启动宿主。MCP 客户端启动单独的 stdio 进程,两者通过当前 Windows 用户的命名管道和每次会话的令牌通信。默认登记目录是 `%LOCALAPPDATA%\Jtcrpa\McpBridge`。`src/install.ts`、`src/connections.ts` 和 `src/registration-lock.ts` 负责登记、绑定和并发更新。浏览器关闭后仍可发现 MCP 工具,并可查询离线状态。
187
- - 原生消息帧最大为 512 KiB,单次业务结果最大为 256 KiB。`page_probe` 支持页面快照、子帧查询、元素/提取探测、点击和滚动。`run_get` 最多列 20 次运行,每次最多读取 50 条日志,默认 10 条。`dataset_list` 默认每页 20 项,最多 50 项。
188
- - 写请求用 UUID 标识。遇到 `OUTCOME_UNKNOWN` 时先查询原请求。扩展最多保留 1,024 条写请求凭据,共 2 MiB。`MCP` 连接断开后,正在运行的工作流由扩展继续管理。
189
- - 扩展仓库与此仓库并列检出时,可在扩展仓库根目录运行下面的命令,对实际分发包进行隔离安装和真实浏览器验收。本例使用 0.4.1。正式发包使用已验收的同一份 `.tgz`。
190
-
191
- ```powershell
192
- node tests/mcp-package/run.mjs ../jtcrpa-mcp-bridge/jtcrpa-mcp-0.4.1.tgz --install-only
193
- node tests/mcp-package/run.mjs ../jtcrpa-mcp-bridge/jtcrpa-mcp-0.4.1.tgz --isolated-host
194
- ```
195
-
196
- ## Maintainer reference
104
+ | Between Mountains and Seas | ¥32.00 |
105
+ | City Strolls | ¥45.00 |
106
+ | Room to Breathe | ¥39.00 |
107
+ | Moonlight on the Page | ¥28.50 |
197
108
 
198
- - `bin/cli.mjs` loads commands from `dist/`. `src/mcp.ts` assembles the connection, authoring, execution and dataset tools in `src/tools/`. `forwarded.ts` relays tool calls to the extension. Tool descriptions are in Chinese. Tool names, argument names and status identifiers are shared by both guides.
199
- - The browser starts the native host through Native Messaging. The MCP client starts a separate stdio process. They communicate through a Windows named pipe restricted to the current user, with a token for each session. Registrations default to `%LOCALAPPDATA%\Jtcrpa\McpBridge`. `src/install.ts`, `src/connections.ts` and `src/registration-lock.ts` manage registrations, bindings and concurrent updates. Tool discovery and offline status queries work while the browser is closed.
200
- - Native frames are limited to 512 KiB, and individual tool results to 256 KiB. `page_probe` supports snapshots, frame queries, element and extraction probes, clicks and scrolling. `run_get` lists at most 20 runs and reads up to 50 log entries, with 10 entries by default. `dataset_list` defaults to 20 items per page and allows up to 50.
201
- - Writes carry a request UUID. Query the original request after `OUTCOME_UNKNOWN`. The extension keeps up to 1,024 write-request records totalling 2 MiB. The extension continues to manage active workflows if the MCP connection drops.
202
- - With the extension and bridge repositories checked out side by side, run the following from the extension repository to test the actual archive in an isolated installation and in real browsers. The example uses version 0.4.1. Publish the same `.tgz` that passed acceptance.
109
+ **Use it again.** Click **Next** in the bookshop, then ask, “Find my saved Bookshop demo workflow, run it on page 2 of the bookshop and tell me how many rows this run saved.” Expect four more rows, including *Little Maps for the Journey* at ¥48.00. For future sessions, open the same browser profile with MCP enabled. The browser and client start the bridge as needed.
203
110
 
204
- ```powershell
205
- node tests/mcp-package/run.mjs ../jtcrpa-mcp-bridge/jtcrpa-mcp-0.4.1.tgz --install-only
206
- node tests/mcp-package/run.mjs ../jtcrpa-mcp-bridge/jtcrpa-mcp-0.4.1.tgz --isolated-host
207
- ```
111
+ [MCP tool calls and their arguments](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/usage.md#tool-calls-for-the-bookshop-example) · [Connection and collection troubleshooting](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/usage.md#troubleshooting) · [Development and publishing](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/publishing.md#english)
package/bin/cli.mjs CHANGED
@@ -10,6 +10,7 @@ const usage = [
10
10
  ' add (--chrome-id <扩展ID> | --firefox-id <扩展ID>) [--instance <UUID>]',
11
11
  ' remove [连接编号]',
12
12
  '客户端接入',
13
+ ' connect-codex (--chrome-id <扩展ID> | --firefox-id <扩展ID>) --instance <UUID> --setup <UUID>',
13
14
  ' config (--connection <连接编号> | --instance <UUID>) [--client codex|claude|deepseek]',
14
15
  ' mcp (--connection <配置中的绑定UUID> | --instance <实例UUID>)',
15
16
  '维护',
@@ -19,11 +20,13 @@ const usage = [
19
20
  function targetOptions(config) {
20
21
  const options = { connection: { type: 'string' }, instance: { type: 'string' } };
21
22
  if (config) options.client = { type: 'string' };
23
+ else options['expect-instance'] = { type: 'string' };
22
24
  const { values, tokens } = parseArgs({ args, options, tokens: true });
23
25
  if (tokens.filter(t => t.name === 'connection' || t.name === 'instance').length !== 1) {
24
26
  throw new Error('Specify one --connection or --instance target.');
25
27
  }
26
28
  if (values.instance !== undefined && !/^[a-f0-9-]{36}$/.test(values.instance)) throw new Error('Invalid instance UUID');
29
+ if (values['expect-instance'] !== undefined && (!values.connection || !/^[a-f0-9-]{36}$/.test(values['expect-instance']))) throw new Error('Invalid expected instance');
27
30
  if (values.connection !== undefined && config && !/^c[1-9]\d*$/.test(values.connection)) throw new Error('Invalid connection number');
28
31
  if (values.connection !== undefined && !config && /^c[1-9]\d*$/.test(values.connection)) {
29
32
  throw new Error('请先用 jtcrpa-mcp config --connection ' + values.connection + ' 生成带绑定 UUID 的客户端配置。');
@@ -31,16 +34,17 @@ function targetOptions(config) {
31
34
  return values;
32
35
  }
33
36
  try {
34
- if (process.platform !== 'win32') throw new Error('This release supports native Windows only.');
37
+ if (!['win32', 'darwin'].includes(process.platform)) throw new Error('This release supports macOS and Windows.');
35
38
  if (command === 'uninstall' && args.length === 1 && ['--help', '-h'].includes(args[0])) {
36
39
  console.log('Usage: jtcrpa-mcp uninstall\n清除当前用户的本机宿主登记和连接。请先关闭浏览器中的 MCP。');
37
40
  }
38
41
  else if (command === 'list') await (await import('../dist/connection-cli.js')).listCommand(args);
39
42
  else if (command === 'remove') await (await import('../dist/connection-cli.js')).removeCommand(args);
40
43
  else if (command === 'native-host') await (await import('../dist/native-host.js')).runNativeHost(args);
44
+ else if (command === 'connect-codex') await (await import('../dist/codex-setup.js')).connectCodex(args);
41
45
  else if (command === 'mcp') {
42
- const { connection, instance } = targetOptions(false);
43
- await (await import('../dist/mcp.js')).serveMcp(connection !== undefined ? { bindingId: connection } : instance);
46
+ const { connection, instance, 'expect-instance': expectedInstanceId } = targetOptions(false);
47
+ await (await import('../dist/mcp.js')).serveMcp(connection !== undefined ? { bindingId: connection, expectedInstanceId } : instance);
44
48
  }
45
49
  else if (command === 'add' || command === 'uninstall') await (await import('../dist/install.js')).manageHostRegistration(command, args);
46
50
  else if (command === 'config') {
@@ -0,0 +1,107 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ const cli = fileURLToPath(new URL('../bin/cli.mjs', import.meta.url));
7
+ function codexCommand(args) {
8
+ let executable = 'codex';
9
+ let batch = false;
10
+ if (process.platform === 'win32') {
11
+ const paths = (process.env.PATH ?? '').split(path.delimiter).map(dir => dir.replace(/^"|"$/g, '')).filter(dir => path.isAbsolute(dir));
12
+ const found = paths.flatMap(dir => ['codex.exe', 'codex.cmd', 'codex.bat'].map(file => path.join(dir, file))).find(file => fs.existsSync(file));
13
+ if (!found)
14
+ throw new Error('请先安装 Codex CLI,确保此终端能够运行 codex。');
15
+ executable = found;
16
+ batch = !found.toLowerCase().endsWith('.exe');
17
+ if (batch) {
18
+ const parts = [found, ...args];
19
+ if (parts.some(part => /["%\r\n]/.test(part)))
20
+ throw new Error('Unsupported character in Windows Codex command path or argument');
21
+ // cmd /s strips one outer quote pair. Every argument keeps its own quotes through the npm/pnpm shim.
22
+ args = ['/d', '/v:off', '/s', '/c', '"' + parts.map(part => '"' + part + '"').join(' ') + '"'];
23
+ executable = path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'cmd.exe');
24
+ }
25
+ }
26
+ return { executable, args, batch };
27
+ }
28
+ function runMcpConfig(action, options) {
29
+ const { executable, args, batch } = codexCommand(['mcp', action, ...options]);
30
+ const result = spawnSync(executable, args, {
31
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
32
+ windowsVerbatimArguments: batch, timeout: 20_000,
33
+ });
34
+ if (result.error)
35
+ throw result.error;
36
+ if (result.status !== 0)
37
+ throw new Error(result.stderr?.trim() || 'Codex MCP 配置失败。');
38
+ return result.stdout ?? '';
39
+ }
40
+ // Recreating a server with "mcp add" would drop custom settings or named tool rules.
41
+ // Only migrate our original command/args table (0.5.0 also wrote enabled=false).
42
+ function isDefaultLegacyRegistration(server) {
43
+ const { name } = server;
44
+ const file = path.join(process.env.CODEX_HOME || path.join(homedir(), '.codex'), 'config.toml');
45
+ if (!fs.existsSync(file))
46
+ return false;
47
+ const config = fs.readFileSync(file, 'utf8');
48
+ const mentions = config.match(new RegExp('(?<![\\w-])' + name + '(?![\\w-])', 'g'));
49
+ if (mentions?.length !== 1 || config.includes('mcp__' + name + '__'))
50
+ return false;
51
+ const sections = config.replace(/\r\n/g, '\n').split(/(?=^\[)/m);
52
+ const header = '[mcp_servers.' + name + ']\n';
53
+ const table = sections.find(section => section.startsWith(header));
54
+ const parent = sections.find(section => section.startsWith('[mcp_servers]\n'));
55
+ const root = sections[0]?.startsWith('[') ? '' : sections[0];
56
+ // The Codex config writer can serialize the same entry as an inline table.
57
+ const fields = table?.slice(header.length) ??
58
+ parent?.match(new RegExp('^' + name + '\\s*=\\s*\\{(.*)\\}\\s*$', 'm'))?.[1] ??
59
+ root?.match(new RegExp('^mcp_servers\\.' + name + '\\s*=\\s*\\{(.*)\\}\\s*$', 'm'))?.[1];
60
+ if (!fields)
61
+ return false;
62
+ // Values have already been checked against the registered transport by Codex.
63
+ const shape = fields.replace(/"(?:\\.|[^"\\\r\n])*"|'[^'\r\n]*'/g, '@')
64
+ .replace(/#[^\n]*/g, '').replace(/\s/g, '');
65
+ return shape.includes('enabled=false') === !server.enabled && shape.includes('command=@') && shape.includes('args=[') &&
66
+ shape.replace(/command=@|enabled=(?:true|false)|args=\[@(?:,@)*,?\]|,/g, '') === '';
67
+ }
68
+ function matchesRegistration(server, args) {
69
+ return server.transport.type === 'stdio' && server.transport.command === process.execPath &&
70
+ JSON.stringify(server.transport.args) === JSON.stringify(args);
71
+ }
72
+ function isGeneratedName(name, base) {
73
+ return name.startsWith(base) && /^(?:_(?:[2-9]|[1-9]\d+))?$/.test(name.slice(base.length));
74
+ }
75
+ function requireEnabled(server) {
76
+ if (!server.enabled)
77
+ throw new Error('Codex 中的 MCP 服务 ' + server.name + ' 已停用。请在 Codex 中启用此服务后重新接入。');
78
+ }
79
+ export function configureServer(bindingId, instanceId, browser, previous) {
80
+ const servers = JSON.parse(runMcpConfig('list', ['--json']));
81
+ const args = [cli, 'mcp', '--connection', bindingId, '--expect-instance', instanceId];
82
+ const base = 'jtcrpa_' + browser;
83
+ const legacyBase = base + '_' + bindingId.slice(0, 8);
84
+ const saved = previous && /^[a-zA-Z0-9_-]+$/.test(previous) ? previous : undefined;
85
+ const matching = servers.filter(server => matchesRegistration(server, args));
86
+ const legacy = matching.find(server => (!saved || server.name === saved) && isGeneratedName(server.name, legacyBase));
87
+ if (legacy && ((!legacy.enabled && legacy.name !== saved) || !isDefaultLegacyRegistration(legacy))) {
88
+ requireEnabled(legacy);
89
+ return legacy.name;
90
+ }
91
+ let name = saved && !isGeneratedName(saved, legacyBase) ? saved : base;
92
+ const existing = matching.find(server => server.name === name) ?? matching.find(server => isGeneratedName(server.name, base) && !isGeneratedName(server.name, legacyBase));
93
+ if (existing) {
94
+ requireEnabled(existing);
95
+ name = existing.name;
96
+ }
97
+ else {
98
+ for (let suffix = 2; servers.some(server => server.name === name); suffix++) {
99
+ name = base + '_' + suffix;
100
+ }
101
+ runMcpConfig('add', [name, '--', process.execPath, ...args]);
102
+ }
103
+ // An interrupted migration can reuse the short entry before retrying removal.
104
+ if (legacy)
105
+ runMcpConfig('remove', [legacy.name]);
106
+ return name;
107
+ }
@@ -0,0 +1,72 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { parseArgs } from 'node:util';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { checkExtensionId, sameExtension } from "./browser-identity.js";
5
+ import { addConnection, connectionFile, connectionName, readConnections } from "./connections.js";
6
+ import { configureServer } from "./codex-client.js";
7
+ import { manageHostRegistration } from "./install.js";
8
+ import { callExtension } from "./ipc.js";
9
+ import { readDiscovery } from "./paths.js";
10
+ import { validInstance } from "./protocol.js";
11
+ import { replaceFile } from "./registration-files.js";
12
+ import { withRegistrationLock } from "./registration-lock.js";
13
+ async function waitForBrowser(target, instanceId, ticket) {
14
+ const deadline = Date.now() + 120_000;
15
+ for (;;) {
16
+ try {
17
+ const discovery = readDiscovery(instanceId);
18
+ if (!sameExtension(target, discovery.caller))
19
+ throw new Error('CONNECTION_INSTANCE_MISMATCH');
20
+ const reply = await callExtension(instanceId, 'codex_setup', { ticket }, 3500);
21
+ if (reply?.instanceId !== instanceId)
22
+ throw new Error('CONNECTION_INSTANCE_MISMATCH');
23
+ return typeof reply.label === 'string' ? reply.label.replace(/[\p{C}]/gu, '').trim().slice(0, 48) : '';
24
+ }
25
+ catch (error) {
26
+ const failure = error;
27
+ if (failure.message === 'UNKNOWN_METHOD')
28
+ throw new Error('请更新九头虫扩展和桥接器,重新开启连接后再接入。');
29
+ if (failure.message === 'CODEX_SETUP_MISMATCH')
30
+ throw new Error('这条命令已失效或属于另一份浏览器配置。请从目标浏览器重新接入。');
31
+ if (!['ENOENT', 'ECONNREFUSED', 'ECONNRESET', 'EPIPE'].includes(failure.code ?? '') &&
32
+ !['BROWSER_OFFLINE', 'BRIDGE_TIMEOUT', 'BRIDGE_CLOSED'].includes(failure.message))
33
+ throw error;
34
+ if (Date.now() >= deadline)
35
+ throw new Error('等待目标浏览器超时。请回到发起接入的九头虫 MCP 页面查看状态,然后重试。');
36
+ await delay(500);
37
+ }
38
+ }
39
+ }
40
+ export async function connectCodex(args) {
41
+ const { values } = parseArgs({ args, options: { 'chrome-id': { type: 'string' }, 'firefox-id': { type: 'string' },
42
+ instance: { type: 'string' }, setup: { type: 'string' } } });
43
+ const chrome = values['chrome-id'], firefox = values['firefox-id'];
44
+ const { instance: instanceId, setup: ticket } = values;
45
+ if (Boolean(chrome) === Boolean(firefox) || !validInstance(instanceId) || !validInstance(ticket)) {
46
+ throw new Error('请从目标浏览器复制完整的 Codex 接入命令。');
47
+ }
48
+ const target = chrome ? { kind: 'chrome', extensionId: chrome } : { kind: 'firefox', extensionId: firefox };
49
+ checkExtensionId(target.kind, target.extensionId);
50
+ await manageHostRegistration('add', ['--' + target.kind + '-id', target.extensionId]);
51
+ console.log('正在等待发起接入的浏览器…');
52
+ const setup = await bindCodexBrowser(target, instanceId, ticket);
53
+ console.log(setup.displayName + ' 已就绪。Codex MCP 服务名为 ' + setup.name);
54
+ }
55
+ export async function bindCodexBrowser(target, instanceId, ticket) {
56
+ const label = await waitForBrowser(target, instanceId, ticket);
57
+ const setup = await withRegistrationLock(() => {
58
+ const store = readConnections();
59
+ const connection = addConnection(store, target, instanceId);
60
+ connection.bindingId ??= randomUUID();
61
+ // A retry after a Codex/config write failure must reuse this exact binding.
62
+ replaceFile(connectionFile(), JSON.stringify(store));
63
+ const name = configureServer(connection.bindingId, instanceId, target.kind + '_' + connection.id, connection.codexServer);
64
+ connection.codexServer = name;
65
+ connection.label = label || undefined;
66
+ replaceFile(connectionFile(), JSON.stringify(store));
67
+ const displayName = connectionName(connection);
68
+ return { name, displayName, bindingId: connection.bindingId };
69
+ });
70
+ await callExtension({ bindingId: setup.bindingId, expectedInstanceId: instanceId }, 'codex_setup', { ticket, bindingId: setup.bindingId, displayName: setup.displayName, serverName: setup.name });
71
+ return setup;
72
+ }
@@ -32,18 +32,21 @@ async function inspectConnections() {
32
32
  return listConnections(confirmed.filter(item => item !== undefined), uncertain);
33
33
  }
34
34
  function printList(list) {
35
+ const command = process.platform === 'win32' ? 'jtcrpa-mcp.cmd' : 'jtcrpa-mcp';
35
36
  if (!list.connections.length)
36
- console.log('尚未登记连接。请从插件的 MCP 页面复制 jtcrpa-mcp.cmd add 命令。');
37
+ console.log(`尚未登记连接。请从插件的 MCP 页面复制 ${command} add 命令。`);
37
38
  for (const [i, item] of list.connections.entries()) {
38
- console.log(`${i + 1}. ${item.id} ${browserNames[item.kind]} ${item.extensionId} ${states[item.status]}`);
39
+ console.log(`${i + 1}. ${item.id} ${browserNames[item.kind]} ${item.label ? item.label + ' ' : ''}${item.extensionId} ${states[item.status]}`);
39
40
  console.log(' 目标实例 ' + (item.instanceId ?? '待选择实例'));
41
+ if (item.codexServer)
42
+ console.log(' Codex 服务 ' + item.codexServer);
40
43
  for (const candidate of item.candidates.filter(x => x.instanceId !== item.instanceId)) {
41
44
  console.log(` 可选实例 ${candidate.instanceId} ${candidateState(candidate.online)}`);
42
45
  }
43
46
  if (!item.instanceId && item.candidates.length) {
44
47
  const flag = item.kind === 'chrome' ? '--chrome-id' : '--firefox-id';
45
48
  const id = item.candidates.length === 1 ? item.candidates[0].instanceId : '<上方实例UUID>';
46
- console.log(` 选择目标 jtcrpa-mcp.cmd add ${flag} ${item.extensionId} --instance ${id}`);
49
+ console.log(` 选择目标 ${command} add ${flag} ${item.extensionId} --instance ${id}`);
47
50
  }
48
51
  }
49
52
  for (const id of list.unconfirmedInstances)
@@ -6,6 +6,10 @@ import { sameExtension } from "./browser-identity.js";
6
6
  import { validInstance } from "./protocol.js";
7
7
  import { withRegistrationLock } from "./registration-lock.js";
8
8
  import { replaceFile } from "./registration-files.js";
9
+ export function connectionName(connection) {
10
+ const name = (connection.kind === 'chrome' ? 'Chrome' : 'Firefox') + ' · ' + connection.id;
11
+ return connection.label ? name + '(' + connection.label + ')' : name;
12
+ }
9
13
  export const connectionFile = () => path.join(bridgeRoot(), 'connections.json');
10
14
  export const validConnectionId = (id) => /^c[1-9]\d*$/.test(id);
11
15
  export function readConnections() {
@@ -90,8 +94,8 @@ export function listConnections(live = listRunningHosts(), uncertain = new Set()
90
94
  && (!record.instanceId || record.instanceId === host.instanceId));
91
95
  const status = selected.some(item => item.online) ? 'online'
92
96
  : awaitingHandshake || selected.some(item => item.online === null) ? 'unconfirmed' : 'offline';
93
- const { id, kind, extensionId, instanceId, bindingId } = record;
94
- return { id, kind, extensionId, instanceId, bindingId, status, candidates };
97
+ const { id, kind, extensionId, instanceId, bindingId, label, codexServer } = record;
98
+ return { id, kind, extensionId, instanceId, bindingId, label, codexServer, status, candidates };
95
99
  });
96
100
  return { connections, unconfirmedInstances: unconfirmed.map(host => host.instanceId) };
97
101
  }