@zenaigc/zenmcp 0.1.6 → 0.1.7
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/INSTALL.md +41 -25
- package/dist/src/doctor.js +8 -2
- package/dist/src/mcp/guidance.js +3 -3
- package/dist/src/mcp/server.js +108 -18
- package/dist/src/setup/cli.js +273 -0
- package/dist/src/setup/credentials.js +157 -0
- package/dist/src/setup/page.js +822 -0
- package/dist/src/setup/server.js +251 -0
- package/dist/src/setup/targets.js +314 -0
- package/dist/src/setup/validate.js +84 -0
- package/package.json +4 -2
- package/skills/zenmcp/SKILL.md +7 -5
- package/skills/zenmcp/widgets/fixtures/zenmcp-account.json +1 -0
- package/skills/zenmcp/widgets/fixtures/zenmcp-asset-roles.json +24 -0
- package/skills/zenmcp/widgets/fixtures/zenmcp-install-checklist.json +1 -1
- package/skills/zenmcp/widgets/fixtures/zenmcp-trim-range.json +19 -0
- package/skills/zenmcp/widgets/zenmcp-account/template.json +7 -0
- package/skills/zenmcp/widgets/zenmcp-account/widget.html +4 -4
- package/skills/zenmcp/widgets/zenmcp-asset-roles/template.json +54 -0
- package/skills/zenmcp/widgets/zenmcp-asset-roles/widget.html +73 -0
- package/skills/zenmcp/widgets/zenmcp-budget-confirm/widget.html +2 -4
- package/skills/zenmcp/widgets/zenmcp-install-checklist/widget.html +3 -5
- package/skills/zenmcp/widgets/zenmcp-model-picker/widget.html +6 -6
- package/skills/zenmcp/widgets/zenmcp-spend-confirm/widget.html +2 -3
- package/skills/zenmcp/widgets/zenmcp-trim-range/template.json +53 -0
- package/skills/zenmcp/widgets/zenmcp-trim-range/widget.html +52 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { ACCOUNT_URL } from '../mcp/guidance.js';
|
|
4
|
+
import { hasSavedCredential, saveCredential, } from './credentials.js';
|
|
5
|
+
import { renderSetupPage } from './page.js';
|
|
6
|
+
import { DEFAULT_ZENMCP_BASE_URL, validateZenmcpKey, } from './validate.js';
|
|
7
|
+
const MAX_BODY_BYTES = 16 * 1024;
|
|
8
|
+
const DEFAULT_IDLE_TIMEOUT_MS = 10 * 60_000;
|
|
9
|
+
function sendJson(res, status, payload) {
|
|
10
|
+
const body = JSON.stringify(payload);
|
|
11
|
+
res.writeHead(status, {
|
|
12
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
13
|
+
'Cache-Control': 'no-store',
|
|
14
|
+
'X-Content-Type-Options': 'nosniff',
|
|
15
|
+
});
|
|
16
|
+
res.end(body);
|
|
17
|
+
}
|
|
18
|
+
function sendHtml(res, html) {
|
|
19
|
+
res.writeHead(200, {
|
|
20
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
21
|
+
'Cache-Control': 'no-store',
|
|
22
|
+
'X-Content-Type-Options': 'nosniff',
|
|
23
|
+
'X-Frame-Options': 'DENY',
|
|
24
|
+
'Referrer-Policy': 'no-referrer',
|
|
25
|
+
'Content-Security-Policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'",
|
|
26
|
+
});
|
|
27
|
+
res.end(html);
|
|
28
|
+
}
|
|
29
|
+
function tokensMatch(expected, actual) {
|
|
30
|
+
if (!actual || actual.length !== expected.length)
|
|
31
|
+
return false;
|
|
32
|
+
return timingSafeEqual(Buffer.from(expected, 'utf8'), Buffer.from(actual, 'utf8'));
|
|
33
|
+
}
|
|
34
|
+
class BodyLimitError extends Error {
|
|
35
|
+
}
|
|
36
|
+
class InvalidJsonError extends Error {
|
|
37
|
+
}
|
|
38
|
+
async function readJsonBody(req) {
|
|
39
|
+
const chunks = [];
|
|
40
|
+
let total = 0;
|
|
41
|
+
for await (const chunk of req) {
|
|
42
|
+
const buf = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
|
|
43
|
+
total += buf.length;
|
|
44
|
+
if (total > MAX_BODY_BYTES) {
|
|
45
|
+
throw new BodyLimitError('request body too large');
|
|
46
|
+
}
|
|
47
|
+
chunks.push(buf);
|
|
48
|
+
}
|
|
49
|
+
const text = Buffer.concat(chunks).toString('utf8').trim();
|
|
50
|
+
if (!text)
|
|
51
|
+
return {};
|
|
52
|
+
let parsed;
|
|
53
|
+
try {
|
|
54
|
+
parsed = JSON.parse(text);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new InvalidJsonError('invalid json');
|
|
58
|
+
}
|
|
59
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
60
|
+
throw new InvalidJsonError('json body must be an object');
|
|
61
|
+
}
|
|
62
|
+
return parsed;
|
|
63
|
+
}
|
|
64
|
+
export async function startSetupServer(options = {}) {
|
|
65
|
+
const env = options.env ?? process.env;
|
|
66
|
+
const baseUrl = options.baseUrl?.trim() || env.ZENMCP_BASE_URL?.trim() || DEFAULT_ZENMCP_BASE_URL;
|
|
67
|
+
const accountUrl = options.accountUrl?.trim() || ACCOUNT_URL;
|
|
68
|
+
const hasEnvOverride = Boolean(env.ZENMCP_TOKEN?.trim());
|
|
69
|
+
const hasExistingFile = await hasSavedCredential(options);
|
|
70
|
+
const sessionToken = randomBytes(24).toString('hex');
|
|
71
|
+
const autoCloseOnSave = options.autoCloseOnSave !== false;
|
|
72
|
+
const autoCloseDelayMs = options.autoCloseDelayMs ?? 120;
|
|
73
|
+
const html = renderSetupPage({
|
|
74
|
+
sessionToken,
|
|
75
|
+
accountUrl,
|
|
76
|
+
hasExistingFile,
|
|
77
|
+
hasEnvOverride,
|
|
78
|
+
});
|
|
79
|
+
const summary = {
|
|
80
|
+
saved: false,
|
|
81
|
+
validated: false,
|
|
82
|
+
timedOut: false,
|
|
83
|
+
hasEnvOverride,
|
|
84
|
+
account: null,
|
|
85
|
+
};
|
|
86
|
+
let resolveClosed;
|
|
87
|
+
const closed = new Promise((resolve) => {
|
|
88
|
+
resolveClosed = resolve;
|
|
89
|
+
});
|
|
90
|
+
let boundPort = 0;
|
|
91
|
+
let server;
|
|
92
|
+
let isClosed = false;
|
|
93
|
+
let idleTimer;
|
|
94
|
+
const shutdown = async () => {
|
|
95
|
+
if (isClosed)
|
|
96
|
+
return { ...summary };
|
|
97
|
+
isClosed = true;
|
|
98
|
+
if (idleTimer) {
|
|
99
|
+
clearTimeout(idleTimer);
|
|
100
|
+
idleTimer = undefined;
|
|
101
|
+
}
|
|
102
|
+
await new Promise((resolve) => {
|
|
103
|
+
server.close(() => resolve());
|
|
104
|
+
server.closeAllConnections?.();
|
|
105
|
+
});
|
|
106
|
+
const finalSummary = { ...summary };
|
|
107
|
+
resolveClosed(finalSummary);
|
|
108
|
+
return finalSummary;
|
|
109
|
+
};
|
|
110
|
+
const resetIdleTimer = () => {
|
|
111
|
+
if (isClosed)
|
|
112
|
+
return;
|
|
113
|
+
if (idleTimer)
|
|
114
|
+
clearTimeout(idleTimer);
|
|
115
|
+
const timeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
|
|
116
|
+
idleTimer = setTimeout(() => {
|
|
117
|
+
summary.timedOut = true;
|
|
118
|
+
void shutdown();
|
|
119
|
+
}, timeoutMs);
|
|
120
|
+
idleTimer.unref?.();
|
|
121
|
+
};
|
|
122
|
+
server = createServer(async (req, res) => {
|
|
123
|
+
resetIdleTimer();
|
|
124
|
+
const expectedHost = `127.0.0.1:${boundPort}`;
|
|
125
|
+
if (req.headers.host !== expectedHost) {
|
|
126
|
+
sendJson(res, 403, { ok: false, message: 'Host 校验未通过,已拒绝访问。' });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const expectedOrigin = `http://${expectedHost}`;
|
|
130
|
+
const origin = req.headers.origin;
|
|
131
|
+
if (origin !== undefined && origin !== expectedOrigin) {
|
|
132
|
+
sendJson(res, 403, { ok: false, message: '跨站请求(Origin 不匹配)已被拒绝。' });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const fetchSite = req.headers['sec-fetch-site'];
|
|
136
|
+
if (typeof fetchSite === 'string' && fetchSite !== 'same-origin' && fetchSite !== 'none') {
|
|
137
|
+
sendJson(res, 403, { ok: false, message: '跨站请求(Sec-Fetch-Site)已被拒绝。' });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const reqPath = new URL(req.url ?? '/', expectedOrigin).pathname;
|
|
141
|
+
if (req.method === 'GET' && reqPath === '/') {
|
|
142
|
+
sendHtml(res, html);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (!reqPath.startsWith('/api/')) {
|
|
146
|
+
sendJson(res, 404, { ok: false, message: '未找到请求的资源。' });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const headerToken = req.headers['x-zenmcp-setup-token'];
|
|
150
|
+
const tokenValue = Array.isArray(headerToken) ? headerToken[0] : headerToken;
|
|
151
|
+
if (!tokensMatch(sessionToken, tokenValue)) {
|
|
152
|
+
sendJson(res, 403, { ok: false, message: '本地会话令牌无效或缺失,已拒绝请求。' });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (req.method === 'GET' && reqPath === '/api/state') {
|
|
156
|
+
sendJson(res, 200, {
|
|
157
|
+
ok: true,
|
|
158
|
+
hasExistingFile: await hasSavedCredential(options),
|
|
159
|
+
hasEnvOverride,
|
|
160
|
+
});
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (req.method !== 'POST') {
|
|
164
|
+
sendJson(res, 405, { ok: false, message: '不支持的请求方法。' });
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
let body;
|
|
168
|
+
try {
|
|
169
|
+
body = await readJsonBody(req);
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
if (error instanceof BodyLimitError) {
|
|
173
|
+
sendJson(res, 413, { ok: false, message: '请求体过大,已拒绝。' });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
sendJson(res, 400, { ok: false, message: '请求体不是合法的 JSON 对象。' });
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (reqPath === '/api/connect') {
|
|
180
|
+
const token = typeof body.token === 'string' ? body.token.trim() : '';
|
|
181
|
+
const validation = await validateZenmcpKey(token, {
|
|
182
|
+
baseUrl,
|
|
183
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
184
|
+
});
|
|
185
|
+
if (!validation.ok) {
|
|
186
|
+
sendJson(res, 400, validation);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
await saveCredential(token, options);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
sendJson(res, 500, {
|
|
194
|
+
ok: false,
|
|
195
|
+
kind: 'write_failed',
|
|
196
|
+
message: '平台 Key 验证通过,但写入本机凭据文件失败,请检查用户配置目录权限与磁盘空间。',
|
|
197
|
+
});
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
summary.validated = true;
|
|
201
|
+
summary.saved = true;
|
|
202
|
+
summary.account = validation.account;
|
|
203
|
+
if (autoCloseOnSave) {
|
|
204
|
+
res.once('finish', () => {
|
|
205
|
+
const timer = setTimeout(() => {
|
|
206
|
+
void shutdown();
|
|
207
|
+
}, autoCloseDelayMs);
|
|
208
|
+
timer.unref?.();
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
sendJson(res, 200, {
|
|
212
|
+
ok: true,
|
|
213
|
+
message: validation.message,
|
|
214
|
+
account: validation.account,
|
|
215
|
+
hasEnvOverride,
|
|
216
|
+
});
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (reqPath === '/api/close') {
|
|
220
|
+
res.once('finish', () => {
|
|
221
|
+
queueMicrotask(() => {
|
|
222
|
+
void shutdown();
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
sendJson(res, 200, { ok: true });
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
sendJson(res, 404, { ok: false, message: '未知接口。' });
|
|
229
|
+
});
|
|
230
|
+
await new Promise((resolve, reject) => {
|
|
231
|
+
server.once('error', reject);
|
|
232
|
+
server.listen(options.port ?? 0, '127.0.0.1', () => {
|
|
233
|
+
server.off('error', reject);
|
|
234
|
+
const addr = server.address();
|
|
235
|
+
if (!addr || typeof addr === 'string') {
|
|
236
|
+
reject(new Error('无法获取本地回环监听端口。'));
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
boundPort = addr.port;
|
|
240
|
+
resolve();
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
resetIdleTimer();
|
|
244
|
+
return {
|
|
245
|
+
url: `http://127.0.0.1:${boundPort}`,
|
|
246
|
+
port: boundPort,
|
|
247
|
+
sessionToken,
|
|
248
|
+
closed,
|
|
249
|
+
close: shutdown,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir, platform } from 'node:os';
|
|
4
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
export class SetupConfigError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.name = 'SetupConfigError';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function getPlatform(env) {
|
|
14
|
+
return env.platform ?? platform();
|
|
15
|
+
}
|
|
16
|
+
function getHomeDir(env) {
|
|
17
|
+
return env.homeDir ?? homedir();
|
|
18
|
+
}
|
|
19
|
+
export function resolveClaudeDesktopPath(env = {}) {
|
|
20
|
+
const os = getPlatform(env);
|
|
21
|
+
const home = getHomeDir(env);
|
|
22
|
+
if (os === 'darwin') {
|
|
23
|
+
return join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
|
|
24
|
+
}
|
|
25
|
+
if (os === 'win32') {
|
|
26
|
+
const appData = env.appDataDir ?? process.env.APPDATA ?? join(home, 'AppData', 'Roaming');
|
|
27
|
+
return join(appData, 'Claude', 'claude_desktop_config.json');
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
export function getSupportedTargets(env = {}) {
|
|
32
|
+
const home = getHomeDir(env);
|
|
33
|
+
const claudeDesktopPath = resolveClaudeDesktopPath(env);
|
|
34
|
+
return [
|
|
35
|
+
{
|
|
36
|
+
id: 'workbuddy',
|
|
37
|
+
label: 'WorkBuddy',
|
|
38
|
+
description: '写入 WorkBuddy 标准 MCP 配置文件(保留其他 MCP 服务)。',
|
|
39
|
+
writable: true,
|
|
40
|
+
defaultPath: join(home, '.workbuddy', 'mcp.json'),
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: 'claude-desktop',
|
|
44
|
+
label: 'Claude Desktop',
|
|
45
|
+
description: claudeDesktopPath
|
|
46
|
+
? '写入 Claude Desktop 标准配置文件 claude_desktop_config.json(默认路径仅支持 macOS / Windows)。'
|
|
47
|
+
: '当前系统无已验证的 Claude Desktop 默认路径,请改用「通用 JSON 配置文件」显式指定路径。',
|
|
48
|
+
writable: claudeDesktopPath !== null,
|
|
49
|
+
defaultPath: claudeDesktopPath,
|
|
50
|
+
...(claudeDesktopPath === null
|
|
51
|
+
? { manualHint: '仅 macOS 与 Windows 已验证 Claude Desktop 默认路径;当前系统请选择「通用 JSON 配置文件」并显式填入 claude_desktop_config.json 路径。' }
|
|
52
|
+
: {}),
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
id: 'generic-json',
|
|
56
|
+
label: '通用 JSON 配置文件(mcpServers)',
|
|
57
|
+
description: '手动指定任意使用标准 mcpServers 结构的本地 .json 配置文件路径。',
|
|
58
|
+
writable: true,
|
|
59
|
+
defaultPath: null,
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
id: 'manual',
|
|
63
|
+
label: '其他客户端(豆包电脑版 / SuperOne / Claude Code 手动导入)',
|
|
64
|
+
description: '不直接修改未验证的私有存储格式;在本地生成配置片段供手动粘贴或导入。',
|
|
65
|
+
writable: false,
|
|
66
|
+
defaultPath: null,
|
|
67
|
+
manualHint: '豆包电脑版:左侧「技能·连接器」→ 添加 MCP 粘贴本地生成的配置片段;SuperOne:在 MCP 设置中添加 mcpServers.zenmcp;Claude Code:请勿在命令行参数中直接传入真实 Key,可在生成本地配置片段后通过客户端设置或配置文件编辑器导入。',
|
|
68
|
+
},
|
|
69
|
+
];
|
|
70
|
+
}
|
|
71
|
+
export function resolveTargetPath(targetId, customPath, env = {}) {
|
|
72
|
+
if (targetId === 'manual')
|
|
73
|
+
return null;
|
|
74
|
+
if (targetId === 'workbuddy')
|
|
75
|
+
return join(getHomeDir(env), '.workbuddy', 'mcp.json');
|
|
76
|
+
if (targetId === 'claude-desktop') {
|
|
77
|
+
const resolved = resolveClaudeDesktopPath(env);
|
|
78
|
+
if (!resolved) {
|
|
79
|
+
throw new SetupConfigError('unsupported_target', '当前系统未核实 Claude Desktop 默认路径,请改用「通用 JSON 配置文件」显式指定路径。');
|
|
80
|
+
}
|
|
81
|
+
return resolved;
|
|
82
|
+
}
|
|
83
|
+
const trimmed = customPath?.trim() ?? '';
|
|
84
|
+
if (!trimmed) {
|
|
85
|
+
throw new SetupConfigError('invalid_path', '请填写通用 JSON 配置文件的本地路径。');
|
|
86
|
+
}
|
|
87
|
+
const expanded = trimmed.startsWith('~/') || trimmed === '~'
|
|
88
|
+
? join(getHomeDir(env), trimmed.slice(1))
|
|
89
|
+
: trimmed;
|
|
90
|
+
return isAbsolute(expanded) ? expanded : resolve(env.cwd ?? process.cwd(), expanded);
|
|
91
|
+
}
|
|
92
|
+
function isPlainObject(value) {
|
|
93
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
94
|
+
}
|
|
95
|
+
function zenmcpCommand(env) {
|
|
96
|
+
return getPlatform(env) === 'win32' ? 'zenmcp.cmd' : 'zenmcp';
|
|
97
|
+
}
|
|
98
|
+
export function buildZenmcpServerEntry(token, env = {}) {
|
|
99
|
+
return {
|
|
100
|
+
command: zenmcpCommand(env),
|
|
101
|
+
env: {
|
|
102
|
+
ZENMCP_TOKEN: token,
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Inspects an existing target config file without ever returning secret values.
|
|
108
|
+
*/
|
|
109
|
+
export async function inspectTargetConfig(targetId, customPath, env = {}) {
|
|
110
|
+
if (targetId === 'manual' || (targetId === 'claude-desktop' && resolveClaudeDesktopPath(env) === null)) {
|
|
111
|
+
return {
|
|
112
|
+
targetId,
|
|
113
|
+
resolvedPath: null,
|
|
114
|
+
writable: false,
|
|
115
|
+
exists: false,
|
|
116
|
+
parseError: null,
|
|
117
|
+
hasZenmcp: false,
|
|
118
|
+
existingCommand: null,
|
|
119
|
+
otherServerNames: [],
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
const resolvedPath = resolveTargetPath(targetId, customPath, env);
|
|
123
|
+
if (!resolvedPath) {
|
|
124
|
+
throw new SetupConfigError('invalid_path', '未能解析目标配置文件路径。');
|
|
125
|
+
}
|
|
126
|
+
let raw;
|
|
127
|
+
try {
|
|
128
|
+
raw = await readFile(resolvedPath, 'utf8');
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
const code = error.code;
|
|
132
|
+
if (code === 'ENOENT') {
|
|
133
|
+
return {
|
|
134
|
+
targetId,
|
|
135
|
+
resolvedPath,
|
|
136
|
+
writable: true,
|
|
137
|
+
exists: false,
|
|
138
|
+
parseError: null,
|
|
139
|
+
hasZenmcp: false,
|
|
140
|
+
existingCommand: null,
|
|
141
|
+
otherServerNames: [],
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
throw new SetupConfigError('write_failed', `无法读取配置文件(${code ?? 'IO_ERROR'})。`);
|
|
145
|
+
}
|
|
146
|
+
if (raw.trim() === '') {
|
|
147
|
+
return {
|
|
148
|
+
targetId,
|
|
149
|
+
resolvedPath,
|
|
150
|
+
writable: true,
|
|
151
|
+
exists: true,
|
|
152
|
+
parseError: null,
|
|
153
|
+
hasZenmcp: false,
|
|
154
|
+
existingCommand: null,
|
|
155
|
+
otherServerNames: [],
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
let parsed;
|
|
159
|
+
try {
|
|
160
|
+
parsed = JSON.parse(raw);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return {
|
|
164
|
+
targetId,
|
|
165
|
+
resolvedPath,
|
|
166
|
+
writable: true,
|
|
167
|
+
exists: true,
|
|
168
|
+
parseError: '现有配置文件不是合法的 JSON,为避免损坏原配置已禁止自动写入。',
|
|
169
|
+
hasZenmcp: false,
|
|
170
|
+
existingCommand: null,
|
|
171
|
+
otherServerNames: [],
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
if (!isPlainObject(parsed)) {
|
|
175
|
+
return {
|
|
176
|
+
targetId,
|
|
177
|
+
resolvedPath,
|
|
178
|
+
writable: true,
|
|
179
|
+
exists: true,
|
|
180
|
+
parseError: '现有配置文件根节点必须是 JSON 对象({ ... })。',
|
|
181
|
+
hasZenmcp: false,
|
|
182
|
+
existingCommand: null,
|
|
183
|
+
otherServerNames: [],
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const servers = parsed.mcpServers;
|
|
187
|
+
if (servers !== undefined && !isPlainObject(servers)) {
|
|
188
|
+
return {
|
|
189
|
+
targetId,
|
|
190
|
+
resolvedPath,
|
|
191
|
+
writable: true,
|
|
192
|
+
exists: true,
|
|
193
|
+
parseError: '现有配置文件的 mcpServers 字段不是 JSON 对象。',
|
|
194
|
+
hasZenmcp: false,
|
|
195
|
+
existingCommand: null,
|
|
196
|
+
otherServerNames: [],
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
const serverMap = isPlainObject(servers) ? servers : {};
|
|
200
|
+
const zenmcpEntry = isPlainObject(serverMap.zenmcp) ? serverMap.zenmcp : null;
|
|
201
|
+
const otherServerNames = Object.keys(serverMap).filter(name => name !== 'zenmcp');
|
|
202
|
+
return {
|
|
203
|
+
targetId,
|
|
204
|
+
resolvedPath,
|
|
205
|
+
writable: true,
|
|
206
|
+
exists: true,
|
|
207
|
+
parseError: null,
|
|
208
|
+
hasZenmcp: Object.hasOwn(serverMap, 'zenmcp'),
|
|
209
|
+
existingCommand: zenmcpEntry && typeof zenmcpEntry.command === 'string' ? zenmcpEntry.command : null,
|
|
210
|
+
otherServerNames,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Safely merges zenmcp into the target mcpServers JSON config and writes atomically.
|
|
215
|
+
* Never overwrites malformed JSON or unconfirmed existing zenmcp entries.
|
|
216
|
+
*/
|
|
217
|
+
export async function saveTargetConfig(targetId, token, options = {}) {
|
|
218
|
+
const env = options.env ?? {};
|
|
219
|
+
if (targetId === 'manual') {
|
|
220
|
+
throw new SetupConfigError('unsupported_target', '手动导入模式不直接写入文件,请复制配置片段到客户端。');
|
|
221
|
+
}
|
|
222
|
+
const resolvedPath = resolveTargetPath(targetId, options.customPath, env);
|
|
223
|
+
if (!resolvedPath) {
|
|
224
|
+
throw new SetupConfigError('invalid_path', '未能解析目标配置文件路径。');
|
|
225
|
+
}
|
|
226
|
+
let root = {};
|
|
227
|
+
let exists = false;
|
|
228
|
+
try {
|
|
229
|
+
const raw = await readFile(resolvedPath, 'utf8');
|
|
230
|
+
exists = true;
|
|
231
|
+
if (raw.trim() !== '') {
|
|
232
|
+
let parsed;
|
|
233
|
+
try {
|
|
234
|
+
parsed = JSON.parse(raw);
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
throw new SetupConfigError('malformed_json', '目标配置文件 JSON 格式无效,已中止写入以保护原有内容。');
|
|
238
|
+
}
|
|
239
|
+
if (!isPlainObject(parsed)) {
|
|
240
|
+
throw new SetupConfigError('invalid_structure', '目标配置文件根节点必须是 JSON 对象,已中止写入。');
|
|
241
|
+
}
|
|
242
|
+
if (parsed.mcpServers !== undefined && !isPlainObject(parsed.mcpServers)) {
|
|
243
|
+
throw new SetupConfigError('invalid_structure', '目标配置文件中的 mcpServers 必须是 JSON 对象,已中止写入。');
|
|
244
|
+
}
|
|
245
|
+
root = { ...parsed };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
if (error instanceof SetupConfigError)
|
|
250
|
+
throw error;
|
|
251
|
+
const code = error.code;
|
|
252
|
+
if (code !== 'ENOENT') {
|
|
253
|
+
throw new SetupConfigError('write_failed', `读取目标配置文件失败(${code ?? 'IO_ERROR'})。`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const existingServers = isPlainObject(root.mcpServers) ? root.mcpServers : {};
|
|
257
|
+
const hasZenmcp = Object.hasOwn(existingServers, 'zenmcp');
|
|
258
|
+
const preservedServers = Object.keys(existingServers).filter(name => name !== 'zenmcp');
|
|
259
|
+
if (hasZenmcp && !options.confirmOverwrite) {
|
|
260
|
+
throw new SetupConfigError('overwrite_required', '检测到已有 zenmcp 配置,请确认替换后再保存。');
|
|
261
|
+
}
|
|
262
|
+
const mergedForWrite = {
|
|
263
|
+
...root,
|
|
264
|
+
mcpServers: {
|
|
265
|
+
...existingServers,
|
|
266
|
+
zenmcp: buildZenmcpServerEntry(token, env),
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
const maskedForPreview = {
|
|
270
|
+
...root,
|
|
271
|
+
mcpServers: {
|
|
272
|
+
...Object.fromEntries(preservedServers.map(name => [name, '[保留原有配置]'])),
|
|
273
|
+
zenmcp: buildZenmcpServerEntry('••••••••(已隐藏,仅写入本机配置)', env),
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
const maskedPreview = JSON.stringify(maskedForPreview, null, 2);
|
|
277
|
+
if (options.dryRun) {
|
|
278
|
+
return {
|
|
279
|
+
targetId,
|
|
280
|
+
resolvedPath,
|
|
281
|
+
replacedExisting: hasZenmcp,
|
|
282
|
+
preservedServers,
|
|
283
|
+
dryRun: true,
|
|
284
|
+
maskedPreview,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
const parentDir = dirname(resolvedPath);
|
|
288
|
+
const tmpPath = join(parentDir, `.zenmcp-tmp-${randomBytes(6).toString('hex')}.json`);
|
|
289
|
+
const content = `${JSON.stringify(mergedForWrite, null, 2)}\n`;
|
|
290
|
+
try {
|
|
291
|
+
await mkdir(parentDir, { recursive: true, mode: 0o700 });
|
|
292
|
+
await writeFile(tmpPath, content, { encoding: 'utf8', mode: 0o600 });
|
|
293
|
+
if (getPlatform(env) !== 'win32') {
|
|
294
|
+
await chmod(tmpPath, 0o600).catch(() => { });
|
|
295
|
+
}
|
|
296
|
+
await rename(tmpPath, resolvedPath);
|
|
297
|
+
if (!exists && getPlatform(env) !== 'win32') {
|
|
298
|
+
await chmod(resolvedPath, 0o600).catch(() => { });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
await rm(tmpPath, { force: true }).catch(() => { });
|
|
303
|
+
const code = error.code;
|
|
304
|
+
throw new SetupConfigError('write_failed', `写入配置文件失败(${code ?? 'IO_ERROR'}),原文件未被覆盖。`);
|
|
305
|
+
}
|
|
306
|
+
return {
|
|
307
|
+
targetId,
|
|
308
|
+
resolvedPath,
|
|
309
|
+
replacedExisting: hasZenmcp,
|
|
310
|
+
preservedServers,
|
|
311
|
+
dryRun: false,
|
|
312
|
+
maskedPreview,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { CloudGateway } from '../gateway/cloud-gateway.js';
|
|
2
|
+
import { GatewayError, redact } from '../gateway/errors.js';
|
|
3
|
+
export const DEFAULT_ZENMCP_BASE_URL = 'https://api.zenaigc.com/api/v1';
|
|
4
|
+
function summarizeAccount(me) {
|
|
5
|
+
const effective = Math.min(me.credits_available, ...(me.daily_credit_limit === null ? [] : [Math.max(0, me.daily_credit_limit - me.used_today)]), ...(me.total_credit_limit === null ? [] : [Math.max(0, me.total_credit_limit - me.used_total)]));
|
|
6
|
+
return {
|
|
7
|
+
credits_available: me.credits_available,
|
|
8
|
+
daily_credit_limit: me.daily_credit_limit,
|
|
9
|
+
total_credit_limit: me.total_credit_limit,
|
|
10
|
+
used_today: me.used_today,
|
|
11
|
+
used_total: me.used_total,
|
|
12
|
+
effective_available_credits: effective,
|
|
13
|
+
credential_kind: me.credential_kind,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Performs read-only account validation via GET /me using Authorization: Bearer.
|
|
18
|
+
* Never echoes the secret or raw server error text.
|
|
19
|
+
*/
|
|
20
|
+
export async function validateZenmcpKey(rawToken, options = {}) {
|
|
21
|
+
const token = rawToken.trim();
|
|
22
|
+
if (!token || /[\r\n\0]/.test(token)) {
|
|
23
|
+
return {
|
|
24
|
+
ok: false,
|
|
25
|
+
kind: 'empty_key',
|
|
26
|
+
message: '请先粘贴有效的平台 Key。',
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
const baseUrl = options.baseUrl?.trim() || DEFAULT_ZENMCP_BASE_URL;
|
|
30
|
+
try {
|
|
31
|
+
const gateway = new CloudGateway({
|
|
32
|
+
baseUrl,
|
|
33
|
+
tokens: { token: async () => token },
|
|
34
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
35
|
+
timeoutMs: options.timeoutMs ?? 15_000,
|
|
36
|
+
});
|
|
37
|
+
const me = await gateway.me();
|
|
38
|
+
const account = summarizeAccount(me);
|
|
39
|
+
const message = account.effective_available_credits === 0
|
|
40
|
+
? '平台 Key 验证通过,已保存连接;当前可支配积分为 0,使用付费能力前请前往官网充值或调整 Key 限额。'
|
|
41
|
+
: '平台 Key 验证通过,本机所有智能体已连通。';
|
|
42
|
+
return {
|
|
43
|
+
ok: true,
|
|
44
|
+
message,
|
|
45
|
+
account,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error instanceof GatewayError) {
|
|
50
|
+
if (error.kind === 'transport') {
|
|
51
|
+
return {
|
|
52
|
+
ok: false,
|
|
53
|
+
kind: 'network_error',
|
|
54
|
+
message: '无法连接到 ZenAIGC 服务(网络异常或超时),请检查本机网络与代理设置后重试。',
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
if (error.status === 401 || error.code === 'invalid_credential') {
|
|
58
|
+
return {
|
|
59
|
+
ok: false,
|
|
60
|
+
kind: 'invalid_credential',
|
|
61
|
+
message: '平台 Key 无效、已过期或已被撤销,请核对后重新粘贴,或前往官网平台 Key 页面新建。',
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
if (error.status === 403 || error.code === 'access_denied') {
|
|
65
|
+
return {
|
|
66
|
+
ok: false,
|
|
67
|
+
kind: 'access_denied',
|
|
68
|
+
message: '该平台 Key 权限不足,无法完成账户校验,请检查 Key 权限配置。',
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
ok: false,
|
|
73
|
+
kind: 'server_error',
|
|
74
|
+
message: `服务端暂时返回异常状态(HTTP ${error.status ?? '未知'}),请稍后重试。`,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
const safeReason = redact(error instanceof Error ? error.message : 'unknown_error', token);
|
|
78
|
+
return {
|
|
79
|
+
ok: false,
|
|
80
|
+
kind: 'network_error',
|
|
81
|
+
message: `连接验证未能完成(${safeReason}),请检查网络或服务地址设置。`,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zenaigc/zenmcp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"zenmcp": "dist/src/mcp/server.js",
|
|
7
|
-
"zenmcp-doctor": "dist/src/doctor.js"
|
|
7
|
+
"zenmcp-doctor": "dist/src/doctor.js",
|
|
8
|
+
"zenmcp-setup": "dist/src/setup/cli.js"
|
|
8
9
|
},
|
|
9
10
|
"files": [
|
|
10
11
|
"dist",
|
|
@@ -16,6 +17,7 @@
|
|
|
16
17
|
},
|
|
17
18
|
"scripts": {
|
|
18
19
|
"doctor": "node dist/src/doctor.js",
|
|
20
|
+
"setup": "node dist/src/setup/cli.js",
|
|
19
21
|
"typecheck": "tsc --noEmit",
|
|
20
22
|
"test": "vitest run",
|
|
21
23
|
"build": "tsc -p tsconfig.build.json && node -e \"require('node:fs').cpSync('templates', 'dist/templates', { recursive: true })\"",
|