jtcrpa-mcp 0.6.0 → 0.6.2

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/bin/cli.mjs CHANGED
@@ -13,6 +13,7 @@ const usage = [
13
13
  ' connect-codex (--chrome-id <扩展ID> | --firefox-id <扩展ID>) --instance <UUID> --setup <UUID>',
14
14
  ' config (--connection <连接编号> | --instance <UUID>) [--client codex|claude|deepseek]',
15
15
  ' mcp (--connection <配置中的绑定UUID> | --instance <实例UUID>)',
16
+ ' macOS 版 Chrome 和 Edge 的 add 和 connect-codex 可加 --chrome-user-data-dir <用户数据根目录>',
16
17
  '维护',
17
18
  ' uninstall 清除当前用户的本机宿主登记',
18
19
  ' --version 显示桥接器版本',
@@ -38,7 +38,7 @@ async function waitForBrowser(target, instanceId, ticket) {
38
38
  }
39
39
  }
40
40
  export async function connectCodex(args) {
41
- const { values } = parseArgs({ args, options: { 'chrome-id': { type: 'string' }, 'firefox-id': { type: 'string' },
41
+ const { values } = parseArgs({ args, options: { 'chrome-user-data-dir': { type: 'string' }, 'chrome-id': { type: 'string' }, 'firefox-id': { type: 'string' },
42
42
  instance: { type: 'string' }, setup: { type: 'string' } } });
43
43
  const chrome = values['chrome-id'], firefox = values['firefox-id'];
44
44
  const { instance: instanceId, setup: ticket } = values;
@@ -47,7 +47,11 @@ export async function connectCodex(args) {
47
47
  }
48
48
  const target = chrome ? { kind: 'chrome', extensionId: chrome } : { kind: 'firefox', extensionId: firefox };
49
49
  checkExtensionId(target.kind, target.extensionId);
50
- await manageHostRegistration('add', ['--' + target.kind + '-id', target.extensionId]);
50
+ const registration = ['--' + target.kind + '-id', target.extensionId];
51
+ const directory = values['chrome-user-data-dir'];
52
+ if (directory !== undefined)
53
+ registration.push('--chrome-user-data-dir', directory);
54
+ await manageHostRegistration('add', registration, { fromRunningBrowser: true });
51
55
  console.log('正在等待发起接入的浏览器…');
52
56
  const setup = await bindCodexBrowser(target, instanceId, ticket);
53
57
  console.log(setup.displayName + ' 已就绪。Codex MCP 服务名为 ' + setup.name);
package/dist/install.js CHANGED
@@ -5,6 +5,7 @@ import { execFileSync } from 'node:child_process';
5
5
  import { parseArgs } from 'node:util';
6
6
  import { bridgeRoot, listRunningHosts } from "./paths.js";
7
7
  import { HOST, validInstance } from "./protocol.js";
8
+ import { defaultChromeDataDir, resolveChromeDataDir } from "./mac-chrome.js";
8
9
  import { withRegistrationLock } from "./registration-lock.js";
9
10
  import { replaceFile } from "./registration-files.js";
10
11
  import { checkExtensionId, sameExtension } from "./browser-identity.js";
@@ -27,7 +28,7 @@ function installationPaths() {
27
28
  const launcher = process.platform === 'darwin' ? 'host.sh' : 'host.cmd';
28
29
  return { root, record: path.join(root, 'installation.json'), launcher: path.join(root, launcher) };
29
30
  }
30
- export async function manageHostRegistration(command, args) {
31
+ export async function manageHostRegistration(command, args, { fromRunningBrowser = false } = {}) {
31
32
  if (command === 'uninstall' && args.length)
32
33
  throw new Error('uninstall does not accept arguments. See jtcrpa-mcp uninstall --help.');
33
34
  const paths = installationPaths();
@@ -35,17 +36,17 @@ export async function manageHostRegistration(command, args) {
35
36
  if (command === 'uninstall')
36
37
  uninstallNativeHost(paths);
37
38
  else {
38
- const { targets, instanceId } = parseBrowserTargets(args);
39
- addNativeHost(paths, targets, instanceId);
39
+ const { targets, instanceId, chromeDataDir } = parseBrowserTargets(args, fromRunningBrowser);
40
+ addNativeHost(paths, targets, instanceId, chromeDataDir);
40
41
  }
41
42
  });
42
43
  }
43
- function addNativeHost(paths, targets, instanceId) {
44
+ function addNativeHost(paths, targets, instanceId, chromeDataDir) {
44
45
  if (process.platform === 'win32' && /["%\r\n]/.test(cli + process.execPath + paths.root))
45
46
  throw new Error('Unsupported character in installation path');
46
- const backup = captureInstallationBackup(paths, targets);
47
+ const backup = captureInstallationBackup(paths, targets, chromeDataDir);
47
48
  const previous = fs.existsSync(paths.record) ? readInstallationRecord(paths.record) : { kinds: [] };
48
- const files = sharedInstallationFiles(paths, previous, targets);
49
+ const files = sharedInstallationFiles(paths, previous, targets, chromeDataDir);
49
50
  const store = readConnections();
50
51
  const register = new Map();
51
52
  for (const target of targets) {
@@ -73,12 +74,18 @@ export async function removeConnection(expected) {
73
74
  if (revoke)
74
75
  store.observed = store.observed.filter(item => !sameExtension(before, item));
75
76
  const paths = installationPaths();
76
- const backup = captureInstallationBackup(paths, revoke ? [before] : []);
77
+ const backup = captureInstallationBackup(paths, []);
77
78
  const files = new Map([[connectionFile(), JSON.stringify(store)]]);
78
79
  if (revoke) {
79
80
  const manifest = manifestPath(paths, before.kind);
80
- if (!backup.registrations.get(before.kind))
81
+ const installation = readInstallationRecord(paths.record);
82
+ const locations = registeredDataDirs(installation, before.kind);
83
+ // Temporary development roots may have disappeared since registration.
84
+ const remaining = locations.filter(dir => dir === undefined || fs.existsSync(dir));
85
+ if (remaining.length && !remaining.some(dir => readHostRegistration(before.kind, dir) === manifest)) {
81
86
  throw new Error('本机宿主登记缺失,请重新运行 add。');
87
+ }
88
+ backup.files.set(manifest, fs.readFileSync(manifest));
82
89
  files.set(manifest, JSON.stringify(createHostManifest(paths.launcher, before, backup.files.get(manifest), 'remove'), null, 2));
83
90
  }
84
91
  commitRegistration(paths, backup, files, new Map());
@@ -107,13 +114,13 @@ function commitRegistration(paths, backup, files, register) {
107
114
  updatedFiles.push(file);
108
115
  }
109
116
  for (const [kind, manifest] of register) {
110
- registerHost(kind, manifest);
117
+ registerHost(kind, manifest, backup.chromeDataDir);
111
118
  updatedRegistry.push(kind);
112
119
  }
113
120
  }
114
121
  catch (error) {
115
122
  for (const kind of updatedRegistry)
116
- restoreHostRegistration(kind, backup.registrations.get(kind), manifestPath(paths, kind));
123
+ restoreHostRegistration(kind, backup.registrations.get(kind), manifestPath(paths, kind), backup.chromeDataDir);
117
124
  for (const file of updatedFiles) {
118
125
  const contents = backup.files.get(file);
119
126
  if (contents)
@@ -133,8 +140,10 @@ function uninstallNativeHost(paths) {
133
140
  const installation = readInstallationRecord(paths.record);
134
141
  for (const kind of installation.kinds) {
135
142
  const manifest = manifestPath(paths, kind);
136
- if (readHostRegistration(kind) === manifest)
137
- unregisterHost(kind);
143
+ for (const directory of registeredDataDirs(installation, kind)) {
144
+ if (readHostRegistration(kind, directory) === manifest)
145
+ unregisterHost(kind, directory);
146
+ }
138
147
  removeFileIfPresent(manifest);
139
148
  }
140
149
  fs.unlinkSync(paths.record);
@@ -142,9 +151,9 @@ function uninstallNativeHost(paths) {
142
151
  removeFileIfPresent(paths.launcher);
143
152
  console.log('Native host unregistered.');
144
153
  }
145
- function parseBrowserTargets(args) {
154
+ function parseBrowserTargets(args, fromRunningBrowser) {
146
155
  const { values } = parseArgs({ args, options: {
147
- 'chrome-id': { type: 'string' }, 'firefox-id': { type: 'string' }, instance: { type: 'string' },
156
+ 'chrome-user-data-dir': { type: 'string' }, 'chrome-id': { type: 'string' }, 'firefox-id': { type: 'string' }, instance: { type: 'string' },
148
157
  } });
149
158
  const chrome = values['chrome-id'];
150
159
  const firefox = values['firefox-id'];
@@ -161,7 +170,12 @@ function parseBrowserTargets(args) {
161
170
  targets.push({ kind: 'firefox', extensionId: firefox });
162
171
  if (values.instance !== undefined && (!validInstance(values.instance) || targets.length !== 1))
163
172
  throw new Error('Specify one browser and a valid instance UUID.');
164
- return { targets, instanceId: values.instance };
173
+ const explicit = values['chrome-user-data-dir'];
174
+ if (explicit !== undefined && (!chrome || process.platform !== 'darwin')) {
175
+ throw new Error('--chrome-user-data-dir 仅适用于 macOS 上的 --chrome-id。');
176
+ }
177
+ const chromeDataDir = chrome && process.platform === 'darwin' ? resolveChromeDataDir(chrome, explicit, fromRunningBrowser) : undefined;
178
+ return { targets, instanceId: values.instance, chromeDataDir };
165
179
  }
166
180
  function prepareInstallationDirectory(root) {
167
181
  fs.mkdirSync(root, { recursive: true, mode: 0o700 });
@@ -186,7 +200,7 @@ function readInstallationRecord(file) {
186
200
  function manifestPath(paths, kind) {
187
201
  return path.join(paths.root, `${kind}.json`);
188
202
  }
189
- function captureInstallationBackup(paths, targets) {
203
+ function captureInstallationBackup(paths, targets, chromeDataDir) {
190
204
  const manifestFiles = targets.map((target) => manifestPath(paths, target.kind));
191
205
  const files = new Map();
192
206
  for (const file of [paths.launcher, paths.record, connectionFile(), ...manifestFiles]) {
@@ -194,15 +208,21 @@ function captureInstallationBackup(paths, targets) {
194
208
  }
195
209
  const registrations = new Map();
196
210
  for (const { kind } of targets) {
197
- const manifest = readHostRegistration(kind);
211
+ const manifest = readHostRegistration(kind, chromeDataDir);
198
212
  if (manifest && manifest !== manifestPath(paths, kind)) {
199
213
  throw new Error(`A different ${kind} host is registered; refusing to overwrite it.`);
200
214
  }
201
215
  registrations.set(kind, manifest);
202
216
  }
203
- return { files, registrations };
217
+ return { files, registrations, chromeDataDir };
204
218
  }
205
- function sharedInstallationFiles(paths, previous, targets) {
219
+ function registeredDataDirs(installation, kind) {
220
+ if (process.platform === 'darwin' && kind === 'chrome') {
221
+ return installation.chromeDataDirs ?? [defaultChromeDataDir()];
222
+ }
223
+ return [undefined];
224
+ }
225
+ function sharedInstallationFiles(paths, previous, targets, chromeDataDir) {
206
226
  // 批处理文件按 UTF-8 写入,先切换代码页再读取含中文的 Node / CLI 路径。
207
227
  const quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
208
228
  const launcher = process.platform === 'darwin'
@@ -214,6 +234,10 @@ function sharedInstallationFiles(paths, previous, targets) {
214
234
  node: process.execPath,
215
235
  cli,
216
236
  };
237
+ if (process.platform === 'darwin' && record.kinds.includes('chrome')) {
238
+ const dirs = previous.chromeDataDirs ?? (previous.kinds.includes('chrome') ? [defaultChromeDataDir()] : []);
239
+ record.chromeDataDirs = [...new Set(chromeDataDir ? [...dirs, chromeDataDir] : dirs)];
240
+ }
217
241
  return new Map([[paths.launcher, launcher], [paths.record, JSON.stringify(record)]]);
218
242
  }
219
243
  function createHostManifest(launcher, target, previous, action) {
@@ -0,0 +1,83 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ export const defaultChromeDataDir = () => path.join(os.homedir(), 'Library/Application Support/Google/Chrome');
6
+ // ps on macOS flattens argv. Keep spaces inside paths and ignore trailing
7
+ // positional arguments (e.g. a URL) after an existing user data directory.
8
+ function dataDirFromCommand(command) {
9
+ const browser = /^\/.*\/(Google Chrome|Microsoft Edge)\.app\/Contents\/MacOS\/\1(?:\s|$)/.exec(command)?.[1];
10
+ if (!browser)
11
+ return;
12
+ const flag = /\s--user-data-dir(?:=|\s+)(.+?)(?=\s--|$)/.exec(command);
13
+ if (!flag)
14
+ return browser === 'Microsoft Edge'
15
+ ? path.join(os.homedir(), 'Library/Application Support/Microsoft Edge') : defaultChromeDataDir();
16
+ let value = flag[1].trim();
17
+ while (path.isAbsolute(value)) {
18
+ if (fs.statSync(path.join(value, 'Local State'), { throwIfNoEntry: false })?.isFile())
19
+ return value;
20
+ const end = value.lastIndexOf(' ');
21
+ if (end < 0)
22
+ break;
23
+ value = value.slice(0, end);
24
+ }
25
+ }
26
+ function runningChromeDirs() {
27
+ const found = spawnSync('/usr/bin/pgrep', ['-u', String(process.getuid()), '-x', '(Google Chrome|Microsoft Edge)'], { encoding: 'utf8' });
28
+ const pids = found.stdout?.trim().split(/\s+/);
29
+ if (found.status !== 0 || !pids?.every(pid => /^\d+$/.test(pid)))
30
+ return new Set();
31
+ const list = spawnSync('/bin/ps', ['-ww', '-p', pids.join(','), '-o', 'command='], { encoding: 'utf8' });
32
+ const dirs = new Set();
33
+ for (const command of (list.stdout ?? '').split('\n')) {
34
+ try {
35
+ const dir = dataDirFromCommand(command.trim());
36
+ if (dir)
37
+ dirs.add(fs.realpathSync(dir));
38
+ }
39
+ catch { /* The process may exit or its profile may be inaccessible. */ }
40
+ }
41
+ return dirs;
42
+ }
43
+ function hasExtension(root, extensionId) {
44
+ let entries;
45
+ try {
46
+ entries = fs.readdirSync(root, { withFileTypes: true });
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ for (const entry of entries) {
52
+ if (!entry.isDirectory())
53
+ continue;
54
+ const profile = path.join(root, entry.name);
55
+ for (const file of ['Secure Preferences', 'Preferences']) {
56
+ try {
57
+ const prefs = JSON.parse(fs.readFileSync(path.join(profile, file), 'utf8'));
58
+ if (Object.hasOwn(prefs?.extensions?.settings ?? {}, extensionId))
59
+ return true;
60
+ }
61
+ catch { /* Most children are not profiles; a running profile may also be updating its preferences. */ }
62
+ }
63
+ }
64
+ return false;
65
+ }
66
+ export function resolveChromeDataDir(extensionId, explicit, fromRunningBrowser = false) {
67
+ if (explicit !== undefined) {
68
+ if (!path.isAbsolute(explicit) || !fs.statSync(path.join(explicit, 'Local State'), { throwIfNoEntry: false })?.isFile()) {
69
+ throw new Error('--chrome-user-data-dir 需要现有 Chrome 用户数据根目录的绝对路径(含 Local State)。');
70
+ }
71
+ return fs.realpathSync(explicit);
72
+ }
73
+ const dirs = runningChromeDirs();
74
+ // connect-codex originates in a live browser. A single root is sufficient
75
+ // even when macOS does not allow enumeration of the profile directory.
76
+ if (fromRunningBrowser && dirs.size === 1)
77
+ return [...dirs][0];
78
+ const matches = [...dirs].filter(dir => hasExtension(dir, extensionId));
79
+ if (matches.length > 1 || (fromRunningBrowser && dirs.size > 1 && !matches.length)) {
80
+ throw new Error('无法唯一确定 Chrome 或 Edge 的用户数据目录,请用 --chrome-user-data-dir 指定目标目录。');
81
+ }
82
+ return matches[0] ?? defaultChromeDataDir();
83
+ }
@@ -3,10 +3,11 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { defaultChromeDataDir } from "./mac-chrome.js";
6
7
  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');
8
+ function macRegistration(kind, chromeDataDir) {
9
+ const root = kind === 'chrome' ? chromeDataDir ?? defaultChromeDataDir() : path.join(os.homedir(), 'Library/Application Support/Mozilla');
10
+ return path.join(root, 'NativeMessagingHosts', HOST + '.json');
10
11
  }
11
12
  function registryKey(kind) {
12
13
  const vendor = kind === 'chrome' ? 'Google\\Chrome' : 'Mozilla';
@@ -15,9 +16,9 @@ function registryKey(kind) {
15
16
  function runRegistryCommand(args) {
16
17
  return spawnSync('reg.exe', args, { encoding: 'utf8', windowsHide: true });
17
18
  }
18
- export function readHostRegistration(kind) {
19
+ export function readHostRegistration(kind, chromeDataDir) {
19
20
  if (process.platform === 'darwin') {
20
- const file = macRegistration(kind);
21
+ const file = macRegistration(kind, chromeDataDir);
21
22
  try {
22
23
  return path.resolve(path.dirname(file), fs.readlinkSync(file));
23
24
  }
@@ -41,9 +42,9 @@ export function readHostRegistration(kind) {
41
42
  const value = JSON.parse(result.stdout);
42
43
  return typeof value === 'string' ? value : undefined;
43
44
  }
44
- export function registerHost(kind, manifest) {
45
+ export function registerHost(kind, manifest, chromeDataDir) {
45
46
  if (process.platform === 'darwin') {
46
- const file = macRegistration(kind);
47
+ const file = macRegistration(kind, chromeDataDir);
47
48
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
48
49
  fs.symlinkSync(manifest, file);
49
50
  return;
@@ -54,19 +55,19 @@ export function registerHost(kind, manifest) {
54
55
  if (result.status !== 0)
55
56
  throw new Error(`Host registration failed: ${result.stderr}`);
56
57
  }
57
- export function unregisterHost(kind) {
58
+ export function unregisterHost(kind, chromeDataDir) {
58
59
  if (process.platform === 'darwin') {
59
- fs.unlinkSync(macRegistration(kind));
60
+ fs.unlinkSync(macRegistration(kind, chromeDataDir));
60
61
  return;
61
62
  }
62
63
  const result = runRegistryCommand(['delete', registryKey(kind), '/f']);
63
64
  if (result.status !== 0)
64
65
  throw new Error(result.stderr || 'Registry removal failed');
65
66
  }
66
- export function restoreHostRegistration(kind, previousPath, manifest) {
67
+ export function restoreHostRegistration(kind, previousPath, manifest, chromeDataDir) {
67
68
  if (process.platform === 'darwin') {
68
- if (readHostRegistration(kind) === manifest)
69
- unregisterHost(kind);
69
+ if (readHostRegistration(kind, chromeDataDir) === manifest)
70
+ unregisterHost(kind, chromeDataDir);
70
71
  return;
71
72
  }
72
73
  // 沿用既有尽力恢复策略,不将恢复命令失败改为新的异常。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jtcrpa-mcp",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "type": "module",
5
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/",