jtcrpa-mcp 0.4.2 → 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
@@ -8,34 +8,36 @@
8
8
 
9
9
  ### 首次连接
10
10
 
11
- 1. **浏览器里找到 MCP 入口。** 在 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)
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
13
  如果菜单里没有这个入口,先确认扩展版本。Chrome 和 Firefox 商店发布的 `2.0.2` 都缺少 MCP。只有商店版时,可向九头虫咨询支持 MCP 的安装包。[联系九头虫](https://jtcrpa.com/contact)
14
14
 
15
- 2. **在 PowerShell 安装桥接器。** 从 Windows 开始菜单打开 PowerShell。需要 Windows PowerShell 5.1 和 Node.js 20.19.0 或更高版本。逐行运行下面的命令,第一行检查 Node.js,最后一行应显示桥接器版本号。[Node.js 下载](https://nodejs.org/en/download)
15
+ 2. **在终端安装桥接器。** 需要 Node.js 20.19.0 或更高版本。macOS 打开「终端」,Windows 打开 PowerShell 5.1。已发布的兼容版本可用下面的命令安装。[Node.js 下载](https://nodejs.org/en/download)
16
16
 
17
- ```powershell
17
+ ```sh
18
18
  node --version
19
19
  npm install -g jtcrpa-mcp
20
20
  jtcrpa-mcp --version
21
21
  ```
22
22
 
23
- 3. **把这个浏览器连上。** 回到扩展的 **MCP 连接 → 注册当前浏览器**,点击复制按钮,把整条命令粘贴到刚才的 PowerShell 并按回车。页面已填好当前扩展的 ID。回到扩展打开 **开启 MCP 连接**,浏览器询问时允许本机通信。看到 **浏览器与本机程序已连接** 再继续。
24
- 4. **把 Codex 连上。** 在同一页的 **接入外部 AI → Codex** 点击 **复制 Codex 接入命令**,在 PowerShell 粘贴并执行。运行 `codex mcp list` 应能看到 `jtcrpa`。打开一个新的 Codex 会话,下面三条消息都发在这个会话里。已安装并登录的 Codex CLI 可以在 PowerShell 输入 `codex` 打开。[安装 Codex CLI](https://developers.openai.com/codex/cli/) · [使用 Claude Code 或 DeepSeek Harness](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/usage.md#客户端配置)
23
+ 此 Codex CLI 流程需要支持浏览器实例绑定的扩展和 0.5.1 或更高版本的桥接器。开发测试可在本仓库运行 `npm run build` 后使用 `npm pack` 生成的本地安装包。
24
+
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#客户端配置)
25
27
 
26
28
  ### 第一次用 MCP 采集书名和价格
27
29
 
28
- **① 打开网页,确认连到了它。** 用刚才连接的浏览器打开书店首页。如果页面显示英文,点页头的 **简体中文**。然后在 **Codex 聊天框**发送第一条消息。[打开书店练习场](https://doc.jtcrpa.com/practice/index.html)
30
+ **① 读取网页。** 在已接入九头虫 MCP 的 AI 对话中发送下面的任务。九头虫会在已绑定的浏览器中打开或复用目标页,沿用该浏览器的登录状态。如果书店显示英文,可在页头切到 **简体中文**。
29
31
 
30
- > 用九头虫 MCP 检查连接,找到我打开的书店练习场标签页。告诉我页面标题,并从页面上读出第一本书的书名和价格。
32
+ > 用九头虫打开 https://doc.jtcrpa.com/practice/index.html ,告诉我页面标题和第一本书的书名、价格。
31
33
 
32
- 返回结果应能跟页面对上,第一本是《山海之间》,价格 ¥32.00。若找错页,先核对打开练习场的浏览器和配置,再继续。
34
+ 练习场首页的第一本书是《山海之间》,价格 ¥32.00。
33
35
 
34
36
  **② 保存一条可复用的规则。** 在同一个聊天里发送第二条消息。
35
37
 
36
38
  > 把书店当前列表页的每本书采成一行,书名列叫 title,价格列叫 price,保留货币符号,只采当前页。先在页面上试采,再把规则保存为工作流「Bookshop demo」,运行时写入数据集 bookshop_demo。告诉我保存的工作流编号,等我确认再运行。
37
39
 
38
- 此时你应拿到 `workflowId`(工作流编号)。也可以在扩展的 **主工作台** 搜索 `Bookshop demo` 查看已保存的规则。
40
+ 此时你应拿到 `workflowId`(工作流编号)。也可以在扩展的 **主工作台** 搜索 `Bookshop demo` 查看已保存的规则。页面会保留,方便检查或试运行。需要关页时,可以自己关闭,也可以在对话里明确指定要关闭的页面。
39
41
 
40
42
  **③ 运行并核对数据。** 收到保存结果后,再单独发第三条消息。
41
43
 
@@ -60,34 +62,36 @@
60
62
 
61
63
  ### First-time setup
62
64
 
63
- 1. **Find MCP in the browser.** On 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)
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)
64
66
 
65
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)
66
68
 
67
- 2. **Install the bridge in PowerShell.** Open PowerShell from the Windows Start menu. You need Windows PowerShell 5.1 and Node.js 20.19.0 or later. Run these lines in order. The first prints your Node.js version and the last should print the bridge version. [Download Node.js](https://nodejs.org/en/download)
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)
68
70
 
69
- ```powershell
71
+ ```sh
70
72
  node --version
71
73
  npm install -g jtcrpa-mcp
72
74
  jtcrpa-mcp --version
73
75
  ```
74
76
 
75
- 3. **Connect this browser.** On the extension’s **MCP connection** page, copy the command under **Register this browser**. Paste it into PowerShell and press Enter. It already contains your extension’s ID. Back in the extension, turn on **Enable MCP connection** and allow native messaging if prompted. Continue when you see **Browser connected to the local program**.
76
- 4. **Connect Codex.** On the same page, under **Connect an AI app → Codex**, click **Copy Codex setup command** and run it in PowerShell. Run `codex mcp list` and look for `jtcrpa`. Open a new Codex session for the three messages below. If the Codex CLI is installed and you’re signed in, type `codex` in PowerShell to start it. [Install the Codex CLI](https://developers.openai.com/codex/cli/) · [Use Claude Code or DeepSeek Harness](https://github.com/zhulinjia/jtcrpa-mcp-bridge/blob/main/docs/usage.md#client-configuration)
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`.
78
+
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)
77
81
 
78
82
  ### Collect your first four books
79
83
 
80
- **① Open the page and check the connection.** Open the bookshop homepage in the browser you just connected. If it appears in Chinese, click **English** in the page header. Send this first message in **Codex chat**. [Open the bookshop playground](https://doc.jtcrpa.com/en/practice/index.html)
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.
81
85
 
82
- > Use Jiutouchong MCP to check the connection and find my open bookshop playground tab. Tell me the page title and read the first book’s title and price from the page.
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.
83
87
 
84
- You should see *Between Mountains and Seas* at ¥32.00. If the result is from a different page, check which browser profile has the bookshop open.
88
+ The first book on the practice homepage is *Between Mountains and Seas* at ¥32.00.
85
89
 
86
90
  **② Save a reusable workflow.** Send this in the same chat.
87
91
 
88
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.
89
93
 
90
- You should receive a `workflowId`. To find the saved rule in the extension, open **Workbench** and search for `Bookshop demo`.
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.
91
95
 
92
96
  **③ Run it and check the saved rows.** Once the client reports that it saved the workflow, send a separate message.
93
97
 
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
  }
package/dist/install.js CHANGED
@@ -24,7 +24,8 @@ export async function clientConfig(target) {
24
24
  }
25
25
  function installationPaths() {
26
26
  const root = bridgeRoot();
27
- return { root, record: path.join(root, 'installation.json'), launcher: path.join(root, 'host.cmd') };
27
+ const launcher = process.platform === 'darwin' ? 'host.sh' : 'host.cmd';
28
+ return { root, record: path.join(root, 'installation.json'), launcher: path.join(root, launcher) };
28
29
  }
29
30
  export async function manageHostRegistration(command, args) {
30
31
  if (command === 'uninstall' && args.length)
@@ -40,7 +41,7 @@ export async function manageHostRegistration(command, args) {
40
41
  });
41
42
  }
42
43
  function addNativeHost(paths, targets, instanceId) {
43
- if (/["%\r\n]/.test(cli + process.execPath + paths.root))
44
+ if (process.platform === 'win32' && /["%\r\n]/.test(cli + process.execPath + paths.root))
44
45
  throw new Error('Unsupported character in installation path');
45
46
  const backup = captureInstallationBackup(paths, targets);
46
47
  const previous = fs.existsSync(paths.record) ? readInstallationRecord(paths.record) : { kinds: [] };
@@ -85,8 +86,11 @@ export async function removeConnection(expected) {
85
86
  }
86
87
  function commitRegistration(paths, backup, files, register) {
87
88
  for (const [file, contents] of files) {
88
- if (backup.files.get(file)?.toString('utf8') === contents)
89
- files.delete(file);
89
+ if (backup.files.get(file)?.toString('utf8') !== contents)
90
+ continue;
91
+ if (process.platform === 'darwin' && file === paths.launcher && (fs.statSync(file).mode & 0o777) !== 0o700)
92
+ continue;
93
+ files.delete(file);
90
94
  }
91
95
  if (files.size === 0 && register.size === 0)
92
96
  return false;
@@ -99,12 +103,12 @@ function commitRegistration(paths, backup, files, register) {
99
103
  const updatedRegistry = [];
100
104
  try {
101
105
  for (const [file, contents] of files) {
102
- replaceFile(file, contents);
106
+ replaceFile(file, contents, file === paths.launcher ? 0o700 : 0o600);
103
107
  updatedFiles.push(file);
104
108
  }
105
109
  for (const [kind, manifest] of register) {
106
- updatedRegistry.push(kind);
107
110
  registerHost(kind, manifest);
111
+ updatedRegistry.push(kind);
108
112
  }
109
113
  }
110
114
  catch (error) {
@@ -113,7 +117,7 @@ function commitRegistration(paths, backup, files, register) {
113
117
  for (const file of updatedFiles) {
114
118
  const contents = backup.files.get(file);
115
119
  if (contents)
116
- replaceFile(file, contents);
120
+ replaceFile(file, contents, file === paths.launcher ? 0o700 : 0o600);
117
121
  else
118
122
  removeFileIfPresent(file);
119
123
  }
@@ -160,7 +164,14 @@ function parseBrowserTargets(args) {
160
164
  return { targets, instanceId: values.instance };
161
165
  }
162
166
  function prepareInstallationDirectory(root) {
163
- fs.mkdirSync(root, { recursive: true });
167
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
168
+ if (process.platform === 'darwin') {
169
+ fs.chmodSync(root, 0o700);
170
+ const instances = path.join(root, 'instances');
171
+ fs.mkdirSync(instances, { recursive: true, mode: 0o700 });
172
+ fs.chmodSync(instances, 0o700);
173
+ return;
174
+ }
164
175
  execFileSync('powershell.exe', [
165
176
  '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
166
177
  '-File', fileURLToPath(new URL('../windows/secure-directory.ps1', import.meta.url)),
@@ -193,7 +204,10 @@ function captureInstallationBackup(paths, targets) {
193
204
  }
194
205
  function sharedInstallationFiles(paths, previous, targets) {
195
206
  // 批处理文件按 UTF-8 写入,先切换代码页再读取含中文的 Node / CLI 路径。
196
- const launcher = `@echo off\r\nchcp 65001 >nul\r\n"${process.execPath}" "${cli}" native-host "%~1" "%~2"\r\n`;
207
+ const quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
208
+ const launcher = process.platform === 'darwin'
209
+ ? `#!/bin/sh\nexport JTCRPA_BRIDGE_HOME=${quote(paths.root)}\nexec ${quote(process.execPath)} ${quote(cli)} native-host "$@"\n`
210
+ : `@echo off\r\nchcp 65001 >nul\r\n"${process.execPath}" "${cli}" native-host "%~1" "%~2"\r\n`;
197
211
  const requestedKinds = targets.map((target) => target.kind);
198
212
  const record = {
199
213
  kinds: [...new Set([...previous.kinds, ...requestedKinds])],
package/dist/ipc.js CHANGED
@@ -8,6 +8,9 @@ export function callExtension(target, method, params = {}, timeoutMs = 50000) {
8
8
  const connection = typeof target === 'string' ? undefined : findBinding(target.bindingId);
9
9
  if (typeof target !== 'string' && !connection)
10
10
  throw new Error('CONNECTION_REMOVED');
11
+ const expectedInstanceId = typeof target === 'string' ? undefined : target.expectedInstanceId;
12
+ if (expectedInstanceId && connection?.instanceId !== expectedInstanceId)
13
+ throw new Error('CONNECTION_INSTANCE_MISMATCH');
11
14
  const instanceId = typeof target === 'string' ? target : connection?.instanceId;
12
15
  if (!instanceId)
13
16
  throw new Error('CONNECTION_INSTANCE_NOT_SELECTED');
@@ -21,7 +24,9 @@ export function callExtension(target, method, params = {}, timeoutMs = 50000) {
21
24
  }
22
25
  if (connection && !sameExtension(connection, record.caller))
23
26
  throw new Error('CONNECTION_INSTANCE_MISMATCH');
24
- const request = JSON.stringify({ token: record.token, method, params }) + '\n';
27
+ const request = JSON.stringify({ token: record.token, method, params,
28
+ expectedInstanceId, codexBinding: expectedInstanceId ? connection?.bindingId : undefined,
29
+ codexAccess: typeof target !== 'string' && target.reportCodexAccess || undefined }) + '\n';
25
30
  if (Buffer.byteLength(request) > MAX_BYTES - 1024) {
26
31
  reject(new Error('MESSAGE_TOO_LARGE'));
27
32
  return;
@@ -46,7 +51,7 @@ export function callExtension(target, method, params = {}, timeoutMs = 50000) {
46
51
  }
47
52
  socket.destroy();
48
53
  });
49
- socket.on('error', reject);
54
+ socket.on('error', (error) => reject(error.code === 'ENOENT' || error.code === 'ECONNREFUSED' ? new Error('BROWSER_OFFLINE') : error));
50
55
  socket.on('end', () => { if (!result.includes(10))
51
56
  reject(new Error('BRIDGE_CLOSED')); });
52
57
  socket.on('close', () => clearTimeout(timer));
package/dist/mcp.js CHANGED
@@ -2,6 +2,7 @@ import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
3
  import { createRequire } from 'node:module';
4
4
  import { validInstance } from "./protocol.js";
5
+ import { connectionName, findBinding } from "./connections.js";
5
6
  import { registerConnectionTools } from "./tools/connection.js";
6
7
  import { registerForwardedTools } from "./tools/forwarded.js";
7
8
  import { authoringTools } from "./tools/authoring.js";
@@ -12,7 +13,10 @@ export async function serveMcp(target) {
12
13
  throw new Error('INVALID_MCP_TARGET');
13
14
  serveStdio(() => {
14
15
  const { version } = createRequire(import.meta.url)('../package.json');
15
- const server = new McpServer({ name: 'jtcrpa', version });
16
+ const binding = typeof target === 'string' || !target.expectedInstanceId ? undefined : findBinding(target.bindingId);
17
+ const server = new McpServer({ name: 'jtcrpa', version, ...(binding ? { title: '九头虫 · ' + connectionName(binding) } : {}) }, {
18
+ instructions: 'For a workflow targeting a URL, use page_open on this server to open it in the bound browser. For an existing tab use browser_context. Pass the returned tabId and pageRef to this same server for inspection, saving and execution. Keep the page open after saving. Call page_close only when the user explicitly asks to close that specific page.',
19
+ });
16
20
  registerConnectionTools(server, target);
17
21
  registerForwardedTools(server, target, authoringTools);
18
22
  registerForwardedTools(server, target, executionTools);
package/dist/methods.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** Native host 白名单与 MCP 工具面同步;不接受任意扩展 RPC。 */
2
- export const METHODS = ['connection_status', 'connection_ping', 'browser_context', 'workflow_contract', 'page_probe', 'workflow_list', 'workflow_get', 'workflow_save', 'workflow_run', 'run_get', 'run_control', 'dataset_list', 'dataset_read'];
2
+ export const METHODS = ['connection_status', 'connection_ping', 'browser_context', 'page_open', 'page_close', 'workflow_contract', 'page_probe', 'workflow_list', 'workflow_get', 'workflow_save', 'workflow_run', 'run_get', 'run_control', 'dataset_list', 'dataset_read'];
@@ -1,6 +1,13 @@
1
1
  import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
2
5
  import { fileURLToPath } from 'node:url';
3
6
  import { HOST } from "./protocol.js";
7
+ function macRegistration(kind) {
8
+ const vendor = kind === 'chrome' ? 'Google/Chrome' : 'Mozilla';
9
+ return path.join(os.homedir(), 'Library/Application Support', vendor, 'NativeMessagingHosts', HOST + '.json');
10
+ }
4
11
  function registryKey(kind) {
5
12
  const vendor = kind === 'chrome' ? 'Google\\Chrome' : 'Mozilla';
6
13
  return `HKCU\\Software\\${vendor}\\NativeMessagingHosts\\${HOST}`;
@@ -9,6 +16,20 @@ function runRegistryCommand(args) {
9
16
  return spawnSync('reg.exe', args, { encoding: 'utf8', windowsHide: true });
10
17
  }
11
18
  export function readHostRegistration(kind) {
19
+ if (process.platform === 'darwin') {
20
+ const file = macRegistration(kind);
21
+ try {
22
+ return path.resolve(path.dirname(file), fs.readlinkSync(file));
23
+ }
24
+ catch (error) {
25
+ const code = error.code;
26
+ if (code === 'ENOENT')
27
+ return undefined;
28
+ if (code === 'EINVAL')
29
+ return file; // Another installer owns this regular manifest.
30
+ throw error;
31
+ }
32
+ }
12
33
  const result = spawnSync('powershell.exe', [
13
34
  '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
14
35
  '-File', fileURLToPath(new URL('../windows/read-registration.ps1', import.meta.url)),
@@ -21,6 +42,12 @@ export function readHostRegistration(kind) {
21
42
  return typeof value === 'string' ? value : undefined;
22
43
  }
23
44
  export function registerHost(kind, manifest) {
45
+ if (process.platform === 'darwin') {
46
+ const file = macRegistration(kind);
47
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
48
+ fs.symlinkSync(manifest, file);
49
+ return;
50
+ }
24
51
  const result = runRegistryCommand([
25
52
  'add', registryKey(kind), '/ve', '/t', 'REG_SZ', '/d', manifest, '/f',
26
53
  ]);
@@ -28,11 +55,20 @@ export function registerHost(kind, manifest) {
28
55
  throw new Error(`Host registration failed: ${result.stderr}`);
29
56
  }
30
57
  export function unregisterHost(kind) {
58
+ if (process.platform === 'darwin') {
59
+ fs.unlinkSync(macRegistration(kind));
60
+ return;
61
+ }
31
62
  const result = runRegistryCommand(['delete', registryKey(kind), '/f']);
32
63
  if (result.status !== 0)
33
64
  throw new Error(result.stderr || 'Registry removal failed');
34
65
  }
35
66
  export function restoreHostRegistration(kind, previousPath, manifest) {
67
+ if (process.platform === 'darwin') {
68
+ if (readHostRegistration(kind) === manifest)
69
+ unregisterHost(kind);
70
+ return;
71
+ }
36
72
  // 沿用既有尽力恢复策略,不将恢复命令失败改为新的异常。
37
73
  if (previousPath) {
38
74
  runRegistryCommand(['add', registryKey(kind), '/ve', '/t', 'REG_SZ', '/d', previousPath, '/f']);
@@ -1,35 +1,60 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import { spawn } from 'node:child_process';
5
3
  import { randomBytes, timingSafeEqual } from 'node:crypto';
6
- import readline from 'node:readline';
7
- import { bridgeRoot, instanceFile } from "./paths.js";
8
- import { MAX_BYTES, nativeDecoder, nativeFrame, validInstance, VERSION } from "./protocol.js";
4
+ import { bridgeRoot, instanceFile, sessionEndpoint } from "./paths.js";
5
+ import { nativeDecoder, nativeFrame, validInstance, VERSION } from "./protocol.js";
9
6
  import { METHODS } from "./methods.js";
10
7
  import { nativeCaller } from "./browser-identity.js";
11
8
  import { rememberInstance } from "./connections.js";
9
+ import { withRegistrationLock } from "./registration-lock.js";
10
+ import { listenForClients } from "./native-transport.js";
11
+ function claimInstance(record) {
12
+ const file = instanceFile(record.instanceId);
13
+ if (fs.existsSync(file)) {
14
+ const old = JSON.parse(fs.readFileSync(file, 'utf8'));
15
+ let alive = true;
16
+ try {
17
+ process.kill(old.pid, 0);
18
+ }
19
+ catch (error) {
20
+ alive = error.code !== 'ESRCH';
21
+ }
22
+ if (alive)
23
+ throw new Error('INSTANCE_CONFLICT');
24
+ if (process.platform === 'darwin' && old.pipe === sessionEndpoint(old.session)) {
25
+ fs.rmSync(old.pipe, { force: true });
26
+ }
27
+ fs.unlinkSync(file);
28
+ }
29
+ fs.writeFileSync(file, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
30
+ }
12
31
  export async function runNativeHost(args) {
13
32
  const caller = nativeCaller(args);
14
- let helper;
15
33
  let record;
34
+ let closeTransport;
16
35
  let claimed = false;
17
36
  let closed = false;
18
- let helloTimer;
19
- let startupTimer;
20
37
  let sequence = 0;
21
38
  const pending = new Map();
22
39
  const send = (value) => process.stdout.write(nativeFrame(value));
23
- const respond = (clientId, body) => helper?.stdin.write(JSON.stringify({ clientId, body }) + '\n');
24
- const fail = (message) => { send({ type: 'error', error: message }); cleanup(); helper?.kill(); process.exitCode = 1; process.stdin.destroy(); };
40
+ const fail = (message) => {
41
+ if (closed)
42
+ return;
43
+ send({ type: 'error', error: message });
44
+ cleanup();
45
+ process.exitCode = 1;
46
+ process.stdin.destroy();
47
+ };
48
+ let timer = setTimeout(() => fail('HANDSHAKE_TIMEOUT'), 10000);
25
49
  function cleanup() {
50
+ if (closed)
51
+ return;
26
52
  closed = true;
27
- clearTimeout(helloTimer);
28
- clearTimeout(startupTimer);
53
+ clearTimeout(timer);
29
54
  for (const item of pending.values())
30
55
  clearTimeout(item.timer);
31
56
  pending.clear();
32
- helper?.stdin.end();
57
+ closeTransport?.();
33
58
  if (record && claimed) {
34
59
  try {
35
60
  const current = JSON.parse(fs.readFileSync(instanceFile(record.instanceId), 'utf8'));
@@ -39,82 +64,71 @@ export async function runNativeHost(args) {
39
64
  catch { /* 已被清理或不存在。 */ }
40
65
  }
41
66
  }
67
+ async function start(current) {
68
+ await withRegistrationLock(() => {
69
+ if (closed)
70
+ return;
71
+ if (!fs.existsSync(path.join(bridgeRoot(), 'installation.json')))
72
+ throw new Error('HOST_NOT_INSTALLED');
73
+ claimInstance(current);
74
+ claimed = true;
75
+ });
76
+ if (closed)
77
+ return;
78
+ await rememberInstance(caller, current.instanceId);
79
+ if (closed)
80
+ return;
81
+ timer = setTimeout(() => fail('PIPE_HOST_START_TIMEOUT'), 10000);
82
+ closeTransport = listenForClients(current.pipe, {
83
+ ready() {
84
+ clearTimeout(timer);
85
+ if (!closed)
86
+ send({ type: 'connected', version: VERSION, instanceId: current.instanceId, codexSetup: true });
87
+ },
88
+ request(request, respond) {
89
+ if (closed)
90
+ return;
91
+ const supplied = Buffer.from(typeof request?.token === 'string' ? request.token : '');
92
+ const expected = Buffer.from(current.token);
93
+ if (!request || supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) {
94
+ respond({ ok: false, error: 'UNAUTHORIZED' });
95
+ return;
96
+ }
97
+ if (request.expectedInstanceId !== undefined && (request.expectedInstanceId !== current.instanceId || !validInstance(request.codexBinding))) {
98
+ respond({ ok: false, error: 'CONNECTION_INSTANCE_MISMATCH' });
99
+ return;
100
+ }
101
+ if (request.method !== 'codex_setup' && !METHODS.includes(request.method ?? '')) {
102
+ respond({ ok: false, error: 'UNKNOWN_METHOD' });
103
+ return;
104
+ }
105
+ const id = ++sequence;
106
+ const timeout = setTimeout(() => { pending.delete(id); respond({ ok: false, error: 'EXTENSION_TIMEOUT' }); }, 45000);
107
+ pending.set(id, { respond, timer: timeout });
108
+ send({ type: 'request', version: VERSION, id, method: request.method, params: request.params,
109
+ expectedInstanceId: request.expectedInstanceId, codexBinding: request.codexBinding, codexAccess: request.codexAccess === true });
110
+ },
111
+ fail,
112
+ closed() { cleanup(); process.stdin.destroy(); },
113
+ });
114
+ }
42
115
  process.once('exit', cleanup);
43
- process.stdin.once('end', () => { cleanup(); });
44
- helloTimer = setTimeout(() => fail('HANDSHAKE_TIMEOUT'), 10000);
45
- const decoder = nativeDecoder((raw) => {
116
+ process.stdin.once('end', cleanup);
117
+ if (process.platform === 'darwin') {
118
+ process.once('SIGTERM', () => { cleanup(); process.stdin.destroy(); });
119
+ }
120
+ const decoder = nativeDecoder(raw => {
121
+ if (closed)
122
+ return;
46
123
  const msg = raw;
47
124
  if (!record) {
48
- clearTimeout(helloTimer);
49
125
  if (msg?.type !== 'hello' || msg.version !== VERSION || !validInstance(msg.instanceId))
50
126
  return fail('INCOMPATIBLE_HANDSHAKE');
51
- const root = bridgeRoot();
52
- if (!fs.existsSync(path.join(root, 'installation.json')))
53
- return fail('HOST_NOT_INSTALLED');
127
+ clearTimeout(timer);
54
128
  const session = randomBytes(16).toString('hex');
55
- record = { version: VERSION, instanceId: msg.instanceId, session, token: randomBytes(32).toString('hex'), pipe: `\\\\.\\pipe\\jtcrpa-mcp-${session}`, pid: process.pid };
56
- record.caller = caller;
57
- const file = instanceFile(record.instanceId);
58
- try {
59
- if (fs.existsSync(file)) {
60
- const old = JSON.parse(fs.readFileSync(file, 'utf8'));
61
- let alive = true;
62
- try {
63
- process.kill(old.pid, 0);
64
- }
65
- catch (error) {
66
- alive = error.code !== 'ESRCH';
67
- }
68
- if (alive)
69
- return fail('INSTANCE_CONFLICT');
70
- fs.unlinkSync(file);
71
- }
72
- fs.writeFileSync(file, JSON.stringify(record), { flag: 'wx' });
73
- claimed = true;
74
- }
75
- catch {
76
- return fail('INSTANCE_CONFLICT');
77
- }
78
- const script = fileURLToPath(new URL('../windows/pipe-server.ps1', import.meta.url));
79
- helper = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script, '-PipeName', `jtcrpa-mcp-${session}`], { windowsHide: true });
80
- startupTimer = setTimeout(() => fail('PIPE_HOST_START_TIMEOUT'), 10000);
81
- helper.stderr.on('data', (chunk) => process.stderr.write(chunk));
82
- helper.on('error', () => fail('PIPE_HOST_START_FAILED'));
83
- helper.on('exit', () => { cleanup(); process.stdin.destroy(); });
84
- readline.createInterface({ input: helper.stdout }).on('line', (line) => {
85
- try {
86
- if (Buffer.byteLength(line) > MAX_BYTES)
87
- return fail('MESSAGE_TOO_LARGE');
88
- const value = JSON.parse(line);
89
- if (value.ready) {
90
- clearTimeout(startupTimer);
91
- const instanceId = record.instanceId;
92
- void rememberInstance(caller, instanceId).then(() => {
93
- if (!closed)
94
- send({ type: 'connected', version: VERSION, instanceId });
95
- }).catch(error => { if (!closed)
96
- fail(error.message); });
97
- return;
98
- }
99
- const supplied = Buffer.from(value.request.token ?? '');
100
- const expected = Buffer.from(record.token);
101
- if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) {
102
- respond(value.clientId, { ok: false, error: 'UNAUTHORIZED' });
103
- return;
104
- }
105
- if (!METHODS.includes(value.request.method ?? '')) {
106
- respond(value.clientId, { ok: false, error: 'UNKNOWN_METHOD' });
107
- return;
108
- }
109
- const id = ++sequence;
110
- const timer = setTimeout(() => { pending.delete(id); respond(value.clientId, { ok: false, error: 'EXTENSION_TIMEOUT' }); }, 45000);
111
- pending.set(id, { clientId: value.clientId, timer });
112
- send({ type: 'request', version: VERSION, id, method: value.request.method, params: value.request.params });
113
- }
114
- catch {
115
- fail('INVALID_IPC_MESSAGE');
116
- }
117
- });
129
+ const current = { version: VERSION, instanceId: msg.instanceId, session, token: randomBytes(32).toString('hex'), pipe: sessionEndpoint(session), pid: process.pid, caller };
130
+ record = current;
131
+ void start(current).catch(error => fail(error.message));
118
132
  return;
119
133
  }
120
134
  if (msg?.type !== 'response' || typeof msg.id !== 'number')
@@ -124,7 +138,7 @@ export async function runNativeHost(args) {
124
138
  return;
125
139
  clearTimeout(item.timer);
126
140
  pending.delete(msg.id);
127
- respond(item.clientId, { ok: msg.ok === true, result: msg.result, error: msg.error });
141
+ item.respond({ ok: msg.ok === true, result: msg.result, error: msg.error });
128
142
  });
129
143
  process.stdin.on('data', (chunk) => { try {
130
144
  decoder(chunk);
@@ -0,0 +1,81 @@
1
+ import fs from 'node:fs';
2
+ import net from 'node:net';
3
+ import readline from 'node:readline';
4
+ import { spawn } from 'node:child_process';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { MAX_BYTES } from "./protocol.js";
7
+ export function listenForClients(endpoint, listener) {
8
+ if (process.platform === 'darwin')
9
+ return listenOnSocket(endpoint, listener);
10
+ const script = fileURLToPath(new URL('../windows/pipe-server.ps1', import.meta.url));
11
+ const pipeName = endpoint.slice(endpoint.lastIndexOf('\\') + 1);
12
+ const helper = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script, '-PipeName', pipeName], { windowsHide: true });
13
+ helper.stderr.on('data', chunk => process.stderr.write(chunk));
14
+ helper.on('error', () => listener.fail('PIPE_HOST_START_FAILED'));
15
+ helper.stdin.on('error', () => listener.fail('PIPE_HOST_CLOSED'));
16
+ helper.on('exit', listener.closed);
17
+ readline.createInterface({ input: helper.stdout }).on('line', line => {
18
+ try {
19
+ if (Buffer.byteLength(line) > MAX_BYTES)
20
+ return listener.fail('MESSAGE_TOO_LARGE');
21
+ const value = JSON.parse(line);
22
+ if (value.ready)
23
+ listener.ready();
24
+ else
25
+ listener.request(value.request, body => {
26
+ helper.stdin.write(JSON.stringify({ clientId: value.clientId, body }) + '\n');
27
+ });
28
+ }
29
+ catch {
30
+ listener.fail('INVALID_IPC_MESSAGE');
31
+ }
32
+ });
33
+ return () => helper.stdin.end();
34
+ }
35
+ function listenOnSocket(endpoint, listener) {
36
+ const clients = new Set();
37
+ const server = net.createServer(socket => {
38
+ clients.add(socket);
39
+ socket.once('close', () => clients.delete(socket));
40
+ socket.on('error', () => socket.destroy());
41
+ socket.setTimeout(55000, () => socket.destroy());
42
+ const chunks = [];
43
+ let bytes = 0;
44
+ socket.on('data', (chunk) => {
45
+ const end = chunk.indexOf(10);
46
+ const part = end < 0 ? chunk : chunk.subarray(0, end);
47
+ bytes += part.length;
48
+ if (bytes >= MAX_BYTES) {
49
+ socket.destroy();
50
+ return;
51
+ }
52
+ chunks.push(part);
53
+ if (end < 0)
54
+ return;
55
+ socket.pause(); // Each connection carries one newline-delimited request.
56
+ try {
57
+ const request = JSON.parse(Buffer.concat(chunks, bytes).toString('utf8'));
58
+ listener.request(request, body => socket.end(JSON.stringify(body) + '\n'));
59
+ }
60
+ catch {
61
+ socket.destroy();
62
+ }
63
+ });
64
+ });
65
+ server.maxConnections = 32;
66
+ server.on('error', () => listener.fail('PIPE_HOST_START_FAILED'));
67
+ server.listen(endpoint, () => {
68
+ try {
69
+ fs.chmodSync(endpoint, 0o600);
70
+ listener.ready();
71
+ }
72
+ catch {
73
+ listener.fail('PIPE_HOST_START_FAILED');
74
+ }
75
+ });
76
+ return () => {
77
+ server.close();
78
+ for (const client of clients)
79
+ client.destroy();
80
+ };
81
+ }
package/dist/paths.js CHANGED
@@ -3,7 +3,28 @@ import os from 'node:os';
3
3
  import fs from 'node:fs';
4
4
  import { recordName, validInstance } from "./protocol.js";
5
5
  export function bridgeRoot() {
6
- return path.resolve(process.env.JTCRPA_BRIDGE_HOME ?? path.join(process.env.LOCALAPPDATA ?? path.join(os.homedir(), 'AppData/Local'), 'Jtcrpa/McpBridge'));
6
+ const base = process.platform === 'darwin'
7
+ ? path.join(os.homedir(), 'Library/Application Support')
8
+ : process.env.LOCALAPPDATA ?? path.join(os.homedir(), 'AppData/Local');
9
+ return path.resolve(process.env.JTCRPA_BRIDGE_HOME ?? path.join(base, 'Jtcrpa/McpBridge'));
10
+ }
11
+ // A user's home and TMPDIR can both exceed Darwin's Unix socket path limit.
12
+ export function macRuntimeDirectory() {
13
+ const uid = process.getuid();
14
+ const directory = `/tmp/jtcrpa-mcp-${uid}`;
15
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
16
+ const stat = fs.lstatSync(directory);
17
+ if (!stat.isDirectory() || stat.uid !== uid || (stat.mode & 0o077) !== 0) {
18
+ throw new Error('Unsafe bridge runtime directory: ' + directory);
19
+ }
20
+ return directory;
21
+ }
22
+ export function sessionEndpoint(session) {
23
+ if (!/^[a-f0-9]{32}$/.test(session))
24
+ throw new Error('INVALID_DISCOVERY');
25
+ return process.platform === 'darwin'
26
+ ? path.join(macRuntimeDirectory(), session + '.sock')
27
+ : `\\\\.\\pipe\\jtcrpa-mcp-${session}`;
7
28
  }
8
29
  export function instanceFile(id) {
9
30
  if (!validInstance(id))
@@ -38,7 +59,7 @@ export function readDiscovery(id) {
38
59
  if (fs.statSync(file).size > 4096)
39
60
  throw new Error('INVALID_DISCOVERY');
40
61
  const record = JSON.parse(fs.readFileSync(file, 'utf8'));
41
- if (record.version !== 1 || record.instanceId !== id || !/^\\\\\.\\pipe\\jtcrpa-mcp-[a-f0-9]{32}$/.test(record.pipe) || !/^[a-f0-9]{64}$/.test(record.token))
62
+ if (record.version !== 1 || record.instanceId !== id || record.pipe !== sessionEndpoint(record.session) || !/^[a-f0-9]{64}$/.test(record.token))
42
63
  throw new Error('INVALID_DISCOVERY');
43
64
  return record;
44
65
  }
@@ -1,9 +1,11 @@
1
1
  import fs from 'node:fs';
2
2
  // 写入者持有登记锁,读者只会看到完整的旧文件或新文件。
3
- export function replaceFile(file, contents) {
3
+ export function replaceFile(file, contents, mode = 0o600) {
4
4
  const temporary = file + '.tmp';
5
5
  try {
6
- fs.writeFileSync(temporary, contents);
6
+ fs.writeFileSync(temporary, contents, { mode });
7
+ if (process.platform === 'darwin')
8
+ fs.chmodSync(temporary, mode);
7
9
  fs.renameSync(temporary, file);
8
10
  }
9
11
  finally {
@@ -1,23 +1,39 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
1
3
  import { createHash } from 'node:crypto';
2
4
  import { createServer } from 'node:net';
3
5
  import { homedir } from 'node:os';
4
6
  import { setTimeout as delay } from 'node:timers/promises';
5
- // 所有安装目录都操作当前用户的同一组 HKCU 注册项。Windows 在进程退出时释放管道名。
6
- const user = createHash('sha256').update(homedir().toLowerCase()).digest('hex');
7
- const endpoint = `\\\\.\\pipe\\jtcrpa-mcp-registration-${user}`;
7
+ import { macRuntimeDirectory } from "./paths.js";
8
+ // Registrations are shared across all installations belonging to one user.
9
+ async function tryRegistrationLock() {
10
+ if (process.platform === 'darwin') {
11
+ // Darwin fcntl.h exposes O_EXLOCK for open(2). Node accepts the flag
12
+ // but does not export it. The kernel releases the lock on process exit.
13
+ const O_EXLOCK = 0x20;
14
+ const { O_CREAT, O_RDWR, O_NONBLOCK, O_NOFOLLOW } = fs.constants;
15
+ const file = path.join(macRuntimeDirectory(), 'registration.lock');
16
+ const fd = fs.openSync(file, O_CREAT | O_RDWR | O_EXLOCK | O_NONBLOCK | O_NOFOLLOW, 0o600);
17
+ return { close(done) { fs.closeSync(fd); done(); } };
18
+ }
19
+ const user = createHash('sha256').update(homedir().toLowerCase()).digest('hex');
20
+ const endpoint = `\\\\.\\pipe\\jtcrpa-mcp-registration-${user}`;
21
+ const server = createServer(socket => socket.destroy());
22
+ await new Promise((resolve, reject) => {
23
+ server.once('error', reject);
24
+ server.listen(endpoint, resolve);
25
+ });
26
+ return server;
27
+ }
8
28
  export async function acquireRegistrationLock() {
9
29
  const deadline = Date.now() + 15000;
10
30
  for (;;) {
11
- const server = createServer(socket => socket.destroy());
12
31
  try {
13
- await new Promise((resolve, reject) => {
14
- server.once('error', reject);
15
- server.listen(endpoint, resolve);
16
- });
17
- return server;
32
+ return await tryRegistrationLock();
18
33
  }
19
34
  catch (error) {
20
- if (error.code !== 'EADDRINUSE')
35
+ const code = error.code;
36
+ if (code !== 'EAGAIN' && code !== 'EADDRINUSE')
21
37
  throw error;
22
38
  if (Date.now() >= deadline)
23
39
  throw new Error('Another bridge command is updating registrations. Try again.');
@@ -28,7 +44,7 @@ export async function acquireRegistrationLock() {
28
44
  export async function withRegistrationLock(action) {
29
45
  const lock = await acquireRegistrationLock();
30
46
  try {
31
- return action();
47
+ return await action();
32
48
  }
33
49
  finally {
34
50
  await new Promise(resolve => lock.close(() => resolve()));
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod/v4';
2
+ import { pageTargetFields } from "./definition.js";
2
3
  const probeNames = [
3
4
  'snapshot',
4
5
  'queryFrames',
@@ -10,11 +11,26 @@ const probeNames = [
10
11
  export const authoringTools = [
11
12
  {
12
13
  name: 'browser_context',
13
- description: '列出当前浏览器实例中的网页标签页摘要。调用页面探针或保存工作流前,先选定明确的 tabId。',
14
+ description: '列出绑定浏览器中的网页及其 tabId、pageRef。用户提供目标网址时可直接调用 page_open。',
14
15
  schema: z.object({}),
15
16
  readOnly: true,
16
17
  openWorld: false,
17
18
  },
19
+ {
20
+ name: 'page_open',
21
+ description: '在此服务绑定的浏览器打开用户指定的 HTTP(S) 网址,唯一精确匹配时复用已有页,否则新开后台页。返回实例、tabId、pageRef 和实际网址。编排时在同一服务使用该页,保存后保留。相同请求重用同一 requestId。',
22
+ schema: z.object({ url: z.url({ protocol: /^https?$/ }), requestId: z.uuid() }),
23
+ readOnly: false,
24
+ destructive: false,
25
+ openWorld: true,
26
+ },
27
+ {
28
+ name: 'page_close',
29
+ description: '仅在用户明确要求关闭指定标签页时调用,使用该页最近的 tabId 和 pageRef。工作流保存或编写完成后默认保留页面。用户的关页意图须来自当前对话。',
30
+ schema: z.object({ ...pageTargetFields, requestId: z.uuid(), userRequested: z.literal(true) }),
31
+ readOnly: false,
32
+ openWorld: false,
33
+ },
18
34
  {
19
35
  name: 'workflow_contract',
20
36
  description: '编排前先读取本契约,获取当前完整编译说明及可用节点工具。' +
@@ -35,7 +51,7 @@ export const authoringTools = [
35
51
  'clean 通过现有沙箱执行。不提供任意 RPC 或 JavaScript 求值接口。',
36
52
  schema: z.object({
37
53
  tool: z.enum(probeNames),
38
- tabId: z.number().int().positive(),
54
+ ...pageTargetFields,
39
55
  frameId: z.number().int().nonnegative().optional(),
40
56
  params: z.record(z.string(), z.unknown()).optional(),
41
57
  requestId: z.uuid().optional(),
@@ -73,7 +89,7 @@ export const authoringTools = [
73
89
  '不得盲目更换请求编号重试。',
74
90
  schema: z.object({
75
91
  requestId: z.uuid(),
76
- tabId: z.number().int().positive(),
92
+ ...pageTargetFields,
77
93
  workflow: z.record(z.string(), z.unknown()),
78
94
  }),
79
95
  readOnly: false,
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod/v4';
2
2
  import { callExtension } from "../ipc.js";
3
- import { findBinding } from "../connections.js";
3
+ import { connectionName, findBinding } from "../connections.js";
4
4
  // 连接状态和回声测试的离线返回不同,保留各自的处理语义。
5
5
  export function registerConnectionTools(server, target) {
6
6
  server.registerTool('connection_status', {
@@ -13,10 +13,15 @@ export function registerConnectionTools(server, target) {
13
13
  let result;
14
14
  try {
15
15
  result = await callExtension(target, 'connection_status', params);
16
+ if (typeof target !== 'string' && target.expectedInstanceId && result && typeof result === 'object') {
17
+ const binding = findBinding(target.bindingId);
18
+ if (binding?.instanceId === target.expectedInstanceId)
19
+ result = { ...result, connectionId: binding.id, browserName: connectionName(binding) };
20
+ }
16
21
  }
17
22
  catch (error) {
18
23
  const binding = typeof target === 'string' ? undefined : findBinding(target.bindingId);
19
- result = { connected: false, instanceId: typeof target === 'string' ? target : binding?.instanceId ?? null,
24
+ result = { connected: false, instanceId: typeof target === 'string' ? target : target.expectedInstanceId ?? binding?.instanceId ?? null,
20
25
  connectionId: binding?.id, error: error.message };
21
26
  }
22
27
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
@@ -1 +1,5 @@
1
- export {};
1
+ import { z } from 'zod/v4';
2
+ export const pageTargetFields = {
3
+ tabId: z.number().int().positive(),
4
+ pageRef: z.string().regex(/^[0-9a-f]{64}$/).describe('原样使用同一服务的 page_open 或 browser_context 返回的页面引用。'),
5
+ };
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod/v4';
2
+ import { pageTargetFields } from "./definition.js";
2
3
  export const executionTools = [
3
4
  {
4
5
  name: 'workflow_run',
@@ -11,7 +12,7 @@ export const executionTools = [
11
12
  schema: z.object({
12
13
  requestId: z.uuid(),
13
14
  workflowId: z.number().int().positive(),
14
- tabId: z.number().int().positive(),
15
+ ...pageTargetFields,
15
16
  }),
16
17
  readOnly: false,
17
18
  openWorld: true,
@@ -1,4 +1,5 @@
1
1
  import { callExtension } from "../ipc.js";
2
+ import { findBinding } from "../connections.js";
2
3
  export function registerForwardedTools(server, target, definitions) {
3
4
  for (const definition of definitions) {
4
5
  server.registerTool(definition.name, {
@@ -7,10 +8,15 @@ export function registerForwardedTools(server, target, definitions) {
7
8
  annotations: {
8
9
  readOnlyHint: definition.readOnly,
9
10
  idempotentHint: definition.readOnly,
10
- destructiveHint: !definition.readOnly,
11
+ destructiveHint: definition.destructive ?? !definition.readOnly,
11
12
  openWorldHint: definition.openWorld,
12
13
  },
13
- }, (params) => forwardToolCall(target, definition, params));
14
+ }, (params) => {
15
+ const source = typeof target !== 'string' && target.expectedInstanceId &&
16
+ /(?:^|[^a-z])codex(?:[^a-z]|$)/i.test(server.server.getClientVersion()?.name ?? '')
17
+ ? { ...target, reportCodexAccess: true } : target;
18
+ return forwardToolCall(source, definition, params);
19
+ });
14
20
  }
15
21
  }
16
22
  async function forwardToolCall(target, definition, params) {
@@ -22,7 +28,17 @@ async function forwardToolCall(target, definition, params) {
22
28
  const failure = {
23
29
  error: error.message,
24
30
  };
25
- if (!definition.readOnly) {
31
+ if (failure.error === 'BROWSER_OFFLINE') {
32
+ const binding = typeof target === 'string' ? undefined : findBinding(target.bindingId);
33
+ failure.message = (binding?.label || '目标浏览器') + '已离线。请在该浏览器中开启九头虫 MCP。';
34
+ }
35
+ else if (failure.error === 'CONNECTION_INSTANCE_MISMATCH' || failure.error === 'CONNECTION_REMOVED') {
36
+ failure.message = '原浏览器绑定已变更,请从目标浏览器重新接入。';
37
+ }
38
+ else if (failure.error === 'UNKNOWN_METHOD' && (definition.name === 'page_open' || definition.name === 'page_close')) {
39
+ failure.message = '当前连接尚未提供此页面工具。请配套更新目标浏览器中的九头虫扩展和本机桥接器。';
40
+ }
41
+ else if (!definition.readOnly) {
26
42
  failure.message = 'Outcome may be unknown. Query connection_status with requestId; do not automatically replay.';
27
43
  }
28
44
  return toToolResult(failure);
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "jtcrpa-mcp",
3
- "version": "0.4.2",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
- "description": "在 Windows 上用 Codex 等 AI 客户端连接九头虫 Agent,创建和运行网页采集工作流、读取数据集。Connect AI clients to Jiutouchong Agent on Windows via MCP to create and run web scraping workflows and read datasets.",
5
+ "description": "在 macOS 和 Windows 上用 Codex 等 AI 客户端连接九头虫 Agent,创建和运行网页采集工作流、读取数据集。Connect AI clients to Jiutouchong Agent on macOS and Windows via MCP to create and run web scraping workflows and read datasets.",
6
6
  "homepage": "https://jtcrpa.com/",
7
7
  "repository": {
8
8
  "type": "git",
@@ -10,7 +10,7 @@
10
10
  },
11
11
  "publishConfig": { "registry": "https://registry.npmjs.org", "access": "public" },
12
12
  "engines": { "node": ">=20.19.0" },
13
- "os": ["win32"],
13
+ "os": ["win32", "darwin"],
14
14
  "bin": { "jtcrpa-mcp": "bin/cli.mjs" },
15
15
  "files": ["bin", "dist", "windows", "README.md"],
16
16
  "scripts": {