zwcad-mcp 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 John Zhang
4
+ Copyright (c) 2026 ZWCAD-2D contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,133 @@
1
- # Temporary Holding Version
1
+ # ZWCAD MCP
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 中望CAD(ZWCAD)MCP 服务,让大模型通过 [MCP 协议](https://modelcontextprotocol.io)直接操控中望CAD 平台与中望机械CAD,完成绘图、标注、图层/块/样式管理,以及图框、标题栏、明细表(BOM)等机械操作。
4
+
5
+ **共计 39 个工具**:平台 26 个(不依赖机械环境)+ 机械 11 个(需中望机械CAD)+ 诊断 2 个。
6
+
7
+ ## 为什么需要 Node 启动器
8
+
9
+ 本服务的业务逻辑是 Python 写的——它通过 Windows COM 驱动 ZWCAD,这部分**无法在 Node 侧等价重写**(COM 类型库解析、SAFEARRAY 编组等能力依赖 `comtypes`)。
10
+
11
+ 而客户端环境通常只保证有 Node,不保证有可用的 Python 依赖。所以本包用一个 Node 启动器抹平差异:
12
+
13
+ ```
14
+ MCP 客户端 ──stdio──► bridge.js ──spawn──► python -m zwcad2d
15
+ ```
16
+
17
+ 启动器自动完成三件事,用户无感:
18
+
19
+ 1. **定位 Python** —— 优先 WorkBuddy 自带,其次系统 Python(需 >= 3.10)
20
+ 2. **准备隔离环境** —— 首次运行在 `%USERPROFILE%\.workbuddy\zwcad-mcp-runtime\` 建 venv 装依赖(约 30~60 秒),之后复用
21
+ 3. **托管服务进程** —— 启动 MCP Server 并原样转发 stdin/stdout
22
+
23
+ ## 环境要求
24
+
25
+ - **Windows 10/11 x64**
26
+ - **中望CAD 或 中望机械CAD** 已启动,且至少打开一张 DWG
27
+ - **Python 3.10+**(缺失时也会尝试 WorkBuddy 自带的 Python)
28
+ - **Node.js 18+**
29
+
30
+ ## 快速开始
31
+
32
+ 无需安装,客户端会自动拉起。把下面整段复制进 MCP 客户端的配置文件即可。
33
+
34
+ ### 方案一:国内镜像(推荐国内用户)
35
+
36
+ ```json
37
+ {
38
+ "mcpServers": {
39
+ "zwcad": {
40
+ "command": "npx",
41
+ "args": ["--registry=https://registry.npmmirror.com", "-y", "zwcad-mcp"],
42
+ "env": { "PYTHONUTF8": "1" }
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ ### 方案二:npm 官方源
49
+
50
+ ```json
51
+ {
52
+ "mcpServers": {
53
+ "zwcad": {
54
+ "command": "npx",
55
+ "args": ["-y", "zwcad-mcp"],
56
+ "env": { "PYTHONUTF8": "1" }
57
+ }
58
+ }
59
+ }
60
+ ```
61
+
62
+ 两者只有 `args` 里的 `--registry` 参数不同,功能完全一致。国内网络用方案一可显著加快首次拉取。
63
+
64
+ 各平台的配置文件位置见 [`connector/`](connector/) 目录。
65
+
66
+ ## 验证接入
67
+
68
+ 让 AI 调用 `zwcad_get_capabilities`:能返回 ZWCAD 版本与工具组清单即表示接入成功。
69
+
70
+ 失败时用 `zwcad_diagnose`(机械问题用 `zwcad_mech_diagnose`)查看逐项探测结果。
71
+
72
+ ## 排障
73
+
74
+ ```bash
75
+ npx -y zwcad-mcp --doctor # 环境诊断:Python 候选、虚拟环境、逐项依赖导入
76
+ npx -y zwcad-mcp --prepare # 只准备运行时后退出
77
+ ```
78
+
79
+ | 现象 | 处理 |
80
+ |---|---|
81
+ | 首次启动等待 30~60 秒 | **正常**,正在安装依赖,之后约 2 秒启动 |
82
+ | 报「未找到可用的 Python」 | 装 Python 3.10+,或设 `ZWCAD_MCP_PYTHON` 指向已有解释器 |
83
+ | 装依赖失败(网络) | 设 `ZWCAD_MCP_PIP_INDEX=https://pypi.tuna.tsinghua.edu.cn/simple` |
84
+ | 运行时损坏 | 删 `%USERPROFILE%\.workbuddy\zwcad-mcp-runtime\` 后重连,自动重建 |
85
+ | 机械工具报 `TYPELIB_NOT_LOADED` | 需中望机械CAD 已启动;平台工具不受影响 |
86
+
87
+ ### 关于 `-2147312566`(加载类型库/DLL 时出错)
88
+
89
+ 这是机械类型库的已知情况,**不是文件缺失或权限问题**。实测根因:`ZwmToolKit.tlb` 内部引用了另一个仅在 ZWCAD 进程运行时才可解析的类型库。
90
+
91
+ - `ZwmToolKit.tlb` 本身可被正常加载,14 个类型中仅 `ZwmBalloonWrapper` 的第二个基类型解析失败
92
+ - 该接口自身 `cFuncs=0`、`cVars=0`,是无方法的空壳,**跳过不损失功能**
93
+ - **处置**:确保 ZWCAD 已启动并打开 DWG,然后完全重启 MCP 连接器
94
+
95
+ ## 环境变量
96
+
97
+ | 变量 | 说明 |
98
+ |---|---|
99
+ | `ZWCAD_MCP_PYTHON` | 指定 Python 解释器路径,跳过自动探测(无效时报错而非静默回退) |
100
+ | `ZWCAD_MCP_PIP_INDEX` | 指定 pip 镜像源 |
101
+
102
+ ## 仓库结构
103
+
104
+ ```
105
+ ├── bridge.js Node 启动器(npm bin 入口)
106
+ ├── runtime/zwcad2d/ Python 源码(本仓库为唯一源头)
107
+ ├── connector/ 各平台连接器元数据
108
+ │ ├── workbuddy/ connector-meta + mcp.json + icon + skills
109
+ │ ├── cursor/ mcp.json
110
+ │ └── claude/ mcp.json
111
+ ├── scripts/build-connector.js 扁平化构建各平台分发包
112
+ └── pyproject.toml Python 包定义(同时可发布到 PyPI)
113
+ ```
114
+
115
+ ## 开发
116
+
117
+ ```bash
118
+ npm run doctor # 环境诊断
119
+ npm run build:connector # 生成 dist/<platform>/ 可提交的分发包
120
+ npm run check:connector # 校验各平台源目录结构
121
+ ```
122
+
123
+ `runtime/zwcad2d/` 是本项目的唯一源码位置。发布 npm 时随包分发,无需再从 PyPI 安装。
124
+
125
+ ## 依赖
126
+
127
+ 安装时自动准备:`fastmcp`、`pyzwcad`、`pyzwcadmech`、`comtypes`、`pywin32`。
128
+
129
+ 第三方组件许可见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
130
+
131
+ ## License
132
+
133
+ MIT
@@ -0,0 +1,16 @@
1
+ # Third-party notices
2
+
3
+ ## ZWCAD Mechanical MCP
4
+
5
+ The platform and mechanical tool implementation is derived from
6
+ `john0909/ZWCAD-Mechanical-MCP`, distributed under the MIT License.
7
+
8
+ - Source: https://github.com/john0909/ZWCAD-Mechanical-MCP
9
+ - Original copyright: Copyright (c) 2026 John Zhang
10
+
11
+ ## ZWCAD Platform MCP
12
+
13
+ The ZWCAD-2D server incorporates compatibility and error-isolation changes from
14
+ `Jerri-Z/ZWCAD-Platform-MCP`, distributed under the MIT License.
15
+
16
+ - Source: https://github.com/Jerri-Z/ZWCAD-Platform-MCP
package/bridge.js ADDED
@@ -0,0 +1,517 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ZWCAD-2D MCP — Node 启动器(bridge)
4
+ *
5
+ * 背景
6
+ * ----
7
+ * WorkBuddy 等客户端默认只有 Node 运行时,没有 uv/uvx,也无法保证用户机器装了
8
+ * 可用的 Python。而本服务是 Python 实现(依赖 COM,无法在 Node 侧等价重写)。
9
+ *
10
+ * 这个脚本就是两者之间的桥梁:用 Node 做“运行时准备 + 进程托管”,
11
+ * 把真正的 MCP 服务作为子进程拉起,并双向转发 stdio。
12
+ *
13
+ * MCP 客户端 ──stdio──► bridge.js ──spawn──► python -m zwcad2d
14
+ *
15
+ * 职责
16
+ * ----
17
+ * 1. 定位可用的 Python(优先 WorkBuddy 自带,其次系统 Python)
18
+ * 2. 首次运行时创建隔离 venv 并安装依赖(约 30~60 秒),之后复用
19
+ * 3. 以子进程方式启动 MCP Server,原样转发 stdin/stdout
20
+ *
21
+ * 关键约束
22
+ * --------
23
+ * stdout 是 MCP 协议通道,**任何日志都不能写 stdout**。
24
+ * 本文件内所有输出一律走 stderr。
25
+ *
26
+ * 用法
27
+ * ----
28
+ * node bridge.js # 正常启动 MCP 服务(供客户端调用)
29
+ * node bridge.js --prepare # 只准备运行时(建 venv + 装依赖),然后退出
30
+ * node bridge.js --doctor # 打印环境诊断信息,然后退出
31
+ */
32
+
33
+ 'use strict';
34
+
35
+ const fs = require('fs');
36
+ const os = require('os');
37
+ const path = require('path');
38
+ const crypto = require('crypto');
39
+ const { spawn, spawnSync } = require('child_process');
40
+
41
+ /* ------------------------------------------------------------------ *
42
+ * 常量
43
+ * ------------------------------------------------------------------ */
44
+
45
+ /** 连接器目录(本文件所在目录) */
46
+ const CONNECTOR_DIR = __dirname;
47
+
48
+ /** 随连接器一起分发的 Python 源码目录(若有,则免去从 PyPI 安装本包) */
49
+ const VENDORED_SRC = path.join(CONNECTOR_DIR, 'runtime');
50
+
51
+ /** 运行时状态目录:虚拟环境与安装标记都放这里,卸载时删掉即可 */
52
+ const STATE_DIR = path.join(os.homedir(), '.workbuddy', 'zwcad-mcp-runtime');
53
+ const VENV_DIR = path.join(STATE_DIR, 'venv');
54
+ const MARKER_FILE = path.join(STATE_DIR, 'installed.json');
55
+
56
+ /** MCP Server 的 Python 入口模块 */
57
+ const ENTRY_MODULE = 'zwcad2d';
58
+
59
+ /** 第三方依赖(与 pyproject.toml 保持一致) */
60
+ const BASE_PACKAGES = [
61
+ 'fastmcp>=2.10.3,<3',
62
+ 'pyzwcad>=0.1',
63
+ 'pyzwcadmech>=0.3.0',
64
+ 'comtypes>=1.1',
65
+ 'pywin32>=305',
66
+ ];
67
+
68
+ /** 依赖自检时关注的模块名(供 --doctor 展示与排障参考) */
69
+ const VERIFY_IMPORTS = ['fastmcp', 'pyzwcad', 'pyzwcadmech', 'comtypes', 'pythoncom'];
70
+
71
+ /** 最低 Python 版本 */
72
+ const MIN_PYTHON = [3, 10];
73
+
74
+ /* ------------------------------------------------------------------ *
75
+ * 日志
76
+ * ------------------------------------------------------------------ */
77
+
78
+ function log(...parts) {
79
+ process.stderr.write('[zwcad-mcp] ' + parts.join(' ') + '\n');
80
+ }
81
+
82
+ function fatal(err) {
83
+ const msg = err && err.stack ? err.stack : String(err);
84
+ log('启动失败:' + msg);
85
+ process.exit(1);
86
+ }
87
+
88
+ /* ------------------------------------------------------------------ *
89
+ * 通用子进程工具
90
+ * ------------------------------------------------------------------ */
91
+
92
+ /**
93
+ * 同步执行并捕获 stdout,失败返回 null(用于探测,不抛异常)。
94
+ *
95
+ * 超时给得比较宽松:Windows 上首次启动 python.exe 可能被杀毒软件扫描,
96
+ * 实测出现过同一路径偶发 20 秒超时被误判为「不可用」的情况。
97
+ * 探测失败会直接导致挑不到可用解释器,代价远大于多等几秒。
98
+ */
99
+ function tryRun(exe, args, options) {
100
+ try {
101
+ const r = spawnSync(exe, args, {
102
+ encoding: 'utf8',
103
+ timeout: 60000,
104
+ windowsHide: true,
105
+ ...options,
106
+ });
107
+ if (r.error || r.status !== 0) return null;
108
+ return (r.stdout || '').trim();
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * 流式执行,输出全部转到 stderr(避免污染 stdout 的 MCP 通道)。
116
+ */
117
+ function runStreaming(exe, args, label) {
118
+ return new Promise((resolve, reject) => {
119
+ log('执行:' + path.basename(exe) + ' ' + args.join(' '));
120
+ let child;
121
+ try {
122
+ child = spawn(exe, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
123
+ } catch (e) {
124
+ reject(new Error(label + ' 无法启动:' + e.message));
125
+ return;
126
+ }
127
+ child.stdout.on('data', (d) => process.stderr.write(d));
128
+ child.stderr.on('data', (d) => process.stderr.write(d));
129
+ child.on('error', reject);
130
+ child.on('close', (code) => {
131
+ if (code === 0) resolve();
132
+ else reject(new Error(label + ' 失败(退出码 ' + code + ')'));
133
+ });
134
+ });
135
+ }
136
+
137
+ /* ------------------------------------------------------------------ *
138
+ * Python 探测
139
+ * ------------------------------------------------------------------ */
140
+
141
+ /**
142
+ * 返回 Python 主次版本号,例如 [3, 13];不可用返回 null。
143
+ *
144
+ * 失败时重试一次:Windows 上 python.exe 首次启动偶尔会异常缓慢
145
+ * (杀毒软件扫描、磁盘繁忙),直接判死会让本可用的解释器被跳过。
146
+ */
147
+ function pythonVersion(exe) {
148
+ const probe = () => {
149
+ const out = tryRun(exe, ['-c', 'import sys;print("%d.%d"%sys.version_info[:2])']);
150
+ if (!out) return null;
151
+ const m = /^(\d+)\.(\d+)$/.exec(out);
152
+ return m ? [Number(m[1]), Number(m[2])] : null;
153
+ };
154
+
155
+ const first = probe();
156
+ if (first) return first;
157
+
158
+ // 一次失败不足以断定不可用,再试一次
159
+ return probe();
160
+ }
161
+
162
+ function versionAtLeast(ver, min) {
163
+ if (!ver) return false;
164
+ if (ver[0] > min[0]) return true;
165
+ if (ver[0] < min[0]) return false;
166
+ return ver[1] >= min[1];
167
+ }
168
+
169
+ /**
170
+ * 按优先级列出候选 Python 解释器。
171
+ *
172
+ * 顺序:显式环境变量 → WorkBuddy 托管 Python → WorkBuddy 安装目录自带 → 系统 PATH
173
+ */
174
+ function pythonCandidates() {
175
+ const list = [];
176
+ const add = (p) => {
177
+ if (p && !list.includes(p)) list.push(p);
178
+ };
179
+
180
+ if (process.env.ZWCAD_MCP_PYTHON) add(process.env.ZWCAD_MCP_PYTHON);
181
+
182
+ // WorkBuddy 托管的 Python:~/.workbuddy/binaries/python/versions/<ver>/python.exe
183
+ const wbPythonRoot = path.join(os.homedir(), '.workbuddy', 'binaries', 'python');
184
+ try {
185
+ const current = fs
186
+ .readFileSync(path.join(wbPythonRoot, 'versions', 'current'), 'utf8')
187
+ .trim();
188
+ if (current) add(path.join(wbPythonRoot, 'versions', current, 'python.exe'));
189
+ } catch {
190
+ /* 没有 current 文件就跳过 */
191
+ }
192
+ try {
193
+ for (const name of fs.readdirSync(path.join(wbPythonRoot, 'versions'))) {
194
+ if (/^\d+\.\d+/.test(name)) add(path.join(wbPythonRoot, 'versions', name, 'python.exe'));
195
+ }
196
+ } catch {
197
+ /* 目录不存在就跳过 */
198
+ }
199
+
200
+ // WorkBuddy 安装目录自带的 Python
201
+ const installRoots = [
202
+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs', 'WorkBuddy'),
203
+ process.env.ProgramFiles && path.join(process.env.ProgramFiles, 'WorkBuddy'),
204
+ process.env['ProgramFiles(x86)'] && path.join(process.env['ProgramFiles(x86)'], 'WorkBuddy'),
205
+ ].filter(Boolean);
206
+ for (const root of installRoots) {
207
+ add(path.join(root, 'resources', 'vendor', 'python', 'python.exe'));
208
+ }
209
+
210
+ // 系统 Python
211
+ add('python');
212
+ add('python3');
213
+
214
+ return list;
215
+ }
216
+
217
+ /**
218
+ * 选出第一个满足最低版本要求的 Python。
219
+ */
220
+ function resolvePython() {
221
+ // 显式指定了就尊重用户意图:不可用时报错,而不是静默回退到别的解释器,
222
+ // 否则用户以为自己指定成功了,实际用的是另一个 Python,排查会很困惑。
223
+ const explicit = process.env.ZWCAD_MCP_PYTHON;
224
+ if (explicit) {
225
+ if (!fs.existsSync(explicit)) {
226
+ throw new Error(
227
+ 'ZWCAD_MCP_PYTHON 指定的解释器不存在:' + explicit + '。请修正该环境变量或删除它改用自动探测。'
228
+ );
229
+ }
230
+ const ver = pythonVersion(explicit);
231
+ if (!ver) {
232
+ throw new Error('ZWCAD_MCP_PYTHON 指定的解释器无法运行:' + explicit);
233
+ }
234
+ if (!versionAtLeast(ver, MIN_PYTHON)) {
235
+ throw new Error(
236
+ 'ZWCAD_MCP_PYTHON 指定的 Python 版本为 ' +
237
+ ver.join('.') +
238
+ ',低于要求的 ' +
239
+ MIN_PYTHON.join('.') +
240
+ ':' +
241
+ explicit
242
+ );
243
+ }
244
+ log('使用 Python ' + ver.join('.') + '(由 ZWCAD_MCP_PYTHON 指定):' + explicit);
245
+ return { exe: explicit, version: ver };
246
+ }
247
+
248
+ const tried = [];
249
+ for (const exe of pythonCandidates()) {
250
+ if (exe !== 'python' && exe !== 'python3' && !fs.existsSync(exe)) continue;
251
+ const ver = pythonVersion(exe);
252
+ if (!ver) {
253
+ tried.push(path.basename(exe) + '(不可用)');
254
+ continue;
255
+ }
256
+ if (!versionAtLeast(ver, MIN_PYTHON)) {
257
+ tried.push(exe + '(' + ver.join('.') + ',版本过低)');
258
+ continue;
259
+ }
260
+ log('使用 Python ' + ver.join('.') + ':' + exe);
261
+ return { exe, version: ver };
262
+ }
263
+ throw new Error(
264
+ '未找到可用的 Python(需要 >= ' +
265
+ MIN_PYTHON.join('.') +
266
+ ')。已尝试:' +
267
+ (tried.join('、') || '无') +
268
+ '。可通过环境变量 ZWCAD_MCP_PYTHON 指定解释器路径。'
269
+ );
270
+ }
271
+
272
+ /* ------------------------------------------------------------------ *
273
+ * 虚拟环境与依赖
274
+ * ------------------------------------------------------------------ */
275
+
276
+ function venvPythonPath() {
277
+ return process.platform === 'win32'
278
+ ? path.join(VENV_DIR, 'Scripts', 'python.exe')
279
+ : path.join(VENV_DIR, 'bin', 'python');
280
+ }
281
+
282
+ /**
283
+ * 依赖清单 + Python 版本的指纹,用于判断是否需要重装。
284
+ */
285
+ function installFingerprint(pythonVersionArr) {
286
+ const h = crypto.createHash('sha256');
287
+ h.update(requiredPackages().join('|'));
288
+ h.update('@');
289
+ h.update(pythonVersionArr ? pythonVersionArr.join('.') : 'unknown');
290
+ return h.digest('hex').slice(0, 16);
291
+ }
292
+
293
+ function readMarker() {
294
+ try {
295
+ return JSON.parse(fs.readFileSync(MARKER_FILE, 'utf8'));
296
+ } catch {
297
+ return null;
298
+ }
299
+ }
300
+
301
+ function writeMarker(fingerprint, pyVer) {
302
+ fs.mkdirSync(STATE_DIR, { recursive: true });
303
+ fs.writeFileSync(
304
+ MARKER_FILE,
305
+ JSON.stringify(
306
+ { fingerprint, python: pyVer ? pyVer.join('.') : null, installedAt: new Date().toISOString() },
307
+ null,
308
+ 2
309
+ )
310
+ );
311
+ }
312
+
313
+ /**
314
+ * 轻量健康检查:直接看 venv 里关键包是否还在(毫秒级,不启动 Python)。
315
+ *
316
+ * 为什么不 import 校验:导入 fastmcp 等全部依赖约需 2.5 秒,
317
+ * 而这段时间会直接叠加到每次启动的延迟上。文件级检查足够发现
318
+ * 「用户误删 / 清理软件删了依赖 / 半途失败的安装」这几类真实故障。
319
+ */
320
+ function quickHealthCheck(venvPython) {
321
+ const sitePackages = path.join(path.dirname(path.dirname(venvPython)), 'Lib', 'site-packages');
322
+ if (!fs.existsSync(sitePackages)) return false;
323
+
324
+ // 这些是缺一不可的关键包(目录名前缀即可判定)
325
+ const critical = ['fastmcp-', 'pyzwcad-', 'pyzwcadmech-', 'comtypes-', 'pywin32-'];
326
+ let entries;
327
+ try {
328
+ entries = fs.readdirSync(sitePackages);
329
+ } catch {
330
+ return false;
331
+ }
332
+ const has = (prefix) =>
333
+ entries.some((e) => e.startsWith(prefix) && e.endsWith('.dist-info'));
334
+
335
+ return critical.every(has);
336
+ }
337
+
338
+ function vendoredSrcOrNull() {
339
+ return fs.existsSync(path.join(VENDORED_SRC, ENTRY_MODULE)) ? VENDORED_SRC : null;
340
+ }
341
+
342
+ /**
343
+ * 本次实际需要安装的包清单。
344
+ *
345
+ * 若连接器内随包带了 Python 源码,则通过 PYTHONPATH 引入,无需再装 zwcad-mcp 本体;
346
+ * 否则改为从 PyPI 安装 `zwcad-mcp`(它自带同样的 39 个工具)。
347
+ */
348
+ function requiredPackages() {
349
+ return vendoredSrcOrNull() ? BASE_PACKAGES.slice() : BASE_PACKAGES.concat('zwcad-mcp');
350
+ }
351
+
352
+ /**
353
+ * 确保 venv 存在且可用,返回 venv 内的 python 路径。
354
+ */
355
+ async function ensureVenv(basePython) {
356
+ const venvPython = venvPythonPath();
357
+
358
+ if (fs.existsSync(venvPython)) {
359
+ const ver = pythonVersion(venvPython);
360
+ if (ver) return venvPython;
361
+ log('检测到虚拟环境不可用,重建中…');
362
+ fs.rmSync(VENV_DIR, { recursive: true, force: true });
363
+ }
364
+
365
+ fs.mkdirSync(STATE_DIR, { recursive: true });
366
+ log('首次运行,创建隔离虚拟环境:' + VENV_DIR);
367
+ await runStreaming(basePython.exe, ['-m', 'venv', VENV_DIR], '创建虚拟环境');
368
+
369
+ if (!fs.existsSync(venvPython)) {
370
+ throw new Error('虚拟环境创建后缺少 python 可执行文件:' + venvPython);
371
+ }
372
+ return venvPython;
373
+ }
374
+
375
+ /**
376
+ * 安装依赖。支持通过 ZWCAD_MCP_PIP_INDEX 指定镜像源。
377
+ */
378
+ async function installDeps(venvPython) {
379
+ const args = ['-m', 'pip', 'install', '--disable-pip-version-check', '--no-input'];
380
+ const index = process.env.ZWCAD_MCP_PIP_INDEX;
381
+ if (index) args.push('-i', index);
382
+
383
+ // 若连接器内已带源码,则本包本身无需从 PyPI 安装(通过 PYTHONPATH 引入)
384
+ args.push(...requiredPackages());
385
+
386
+ log('首次运行,安装依赖(约 30~60 秒,请稍候)…');
387
+ await runStreaming(venvPython, args, '安装依赖');
388
+ }
389
+
390
+ /**
391
+ * 准备运行时:确保 venv + 依赖就绪,返回 venv python 路径。
392
+ */
393
+ async function prepareRuntime() {
394
+ const base = resolvePython();
395
+ const fingerprint = installFingerprint(base.version);
396
+ const venvPython = await ensureVenv(base);
397
+
398
+ const marker = readMarker();
399
+ const upToDate = marker && marker.fingerprint === fingerprint;
400
+
401
+ // 标记有效仍需确认依赖文件还在:用户可能手工删过 venv 里的包
402
+ if (upToDate && quickHealthCheck(venvPython)) {
403
+ return venvPython;
404
+ }
405
+
406
+ if (upToDate) {
407
+ log('检测到依赖缺失或损坏,重新安装…');
408
+ }
409
+ await installDeps(venvPython);
410
+ writeMarker(fingerprint, base.version);
411
+ log('依赖安装完成。');
412
+ return venvPython;
413
+ }
414
+
415
+ /* ------------------------------------------------------------------ *
416
+ * 启动(代理模式)
417
+ * ------------------------------------------------------------------ */
418
+
419
+ /**
420
+ * 以代理模式启动:立即完成 MCP 握手,Python 运行时在后台准备。
421
+ *
422
+ * 这样首次使用(需安装约 90 个 Python 依赖,实测 40~70 秒)也不会
423
+ * 触发客户端的 initialize 超时(通常 30 秒)。
424
+ *
425
+ * 具体协议处理见 lib/proxy.js。
426
+ */
427
+ function startWithProxy() {
428
+ const { createProxy } = require('./lib/proxy');
429
+ createProxy({
430
+ cwd: CONNECTOR_DIR,
431
+ version: pkgVersion(),
432
+ childArgs: ['-m', ENTRY_MODULE],
433
+ log,
434
+ ensureRuntime: async () => {
435
+ // 每次都要重新探测:用户可能刚装了 Python 或修好了环境
436
+ const py = await prepareRuntime();
437
+ return py;
438
+ },
439
+ });
440
+ }
441
+
442
+ function pkgVersion() {
443
+ try {
444
+ return JSON.parse(fs.readFileSync(path.join(CONNECTOR_DIR, 'package.json'), 'utf8')).version;
445
+ } catch {
446
+ return '0.0.0';
447
+ }
448
+ }
449
+
450
+ /* ------------------------------------------------------------------ *
451
+ * 诊断
452
+ * ------------------------------------------------------------------ */
453
+
454
+ function doctor() {
455
+ log('连接器目录:' + CONNECTOR_DIR);
456
+ log('运行时状态目录:' + STATE_DIR);
457
+ log('随包源码:' + (vendoredSrcOrNull() || '(无,将使用已安装的 zwcad-mcp 包)'));
458
+ log('--- Python 候选 ---');
459
+ for (const exe of pythonCandidates()) {
460
+ if (exe !== 'python' && exe !== 'python3' && !fs.existsSync(exe)) {
461
+ log(' [缺失] ' + exe);
462
+ continue;
463
+ }
464
+ const ver = pythonVersion(exe);
465
+ log(' ' + (ver ? '[可用 ' + ver.join('.') + ']' : '[不可用] ') + ' ' + exe);
466
+ }
467
+ const venvPython = venvPythonPath();
468
+ if (fs.existsSync(venvPython)) {
469
+ const ver = pythonVersion(venvPython);
470
+ log('--- 虚拟环境 ---');
471
+ log(' 路径:' + venvPython + '(Python ' + (ver ? ver.join('.') : '未知') + ')');
472
+ log(' 依赖文件完整:' + (quickHealthCheck(venvPython) ? '是' : '否'));
473
+ const m = readMarker();
474
+ log(' 安装标记:' + (m ? JSON.stringify(m) : '无'));
475
+
476
+ // 逐个 import 验证,给出具体是哪个依赖坏了(仅诊断模式,慢一些无妨)
477
+ log(' --- 逐项导入验证 ---');
478
+ const env = { ...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' };
479
+ const src = vendoredSrcOrNull();
480
+ if (src) env.PYTHONPATH = env.PYTHONPATH ? src + path.delimiter + env.PYTHONPATH : src;
481
+ for (const mod of VERIFY_IMPORTS) {
482
+ const r = spawnSync(venvPython, ['-c', 'import ' + mod], {
483
+ encoding: 'utf8',
484
+ timeout: 60000,
485
+ windowsHide: true,
486
+ env,
487
+ });
488
+ log(' ' + (r.status === 0 ? '[OK] ' : '[失败] ') + mod);
489
+ }
490
+ } else {
491
+ log('--- 虚拟环境 --- 尚未创建(首次启动时会自动创建)');
492
+ }
493
+ }
494
+
495
+ /* ------------------------------------------------------------------ *
496
+ * 入口
497
+ * ------------------------------------------------------------------ */
498
+
499
+ async function main() {
500
+ const argv = process.argv.slice(2);
501
+
502
+ if (argv.includes('--doctor')) {
503
+ doctor();
504
+ return;
505
+ }
506
+
507
+ if (argv.includes('--prepare')) {
508
+ await prepareRuntime();
509
+ log('运行时准备完毕。');
510
+ return;
511
+ }
512
+
513
+ // 正常启动:走代理模式,先握手再后台准备运行时
514
+ startWithProxy();
515
+ }
516
+
517
+ main().catch(fatal);