serena-mcp-gateway 1.2.0 → 1.3.1

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
@@ -14,12 +14,17 @@ npm i -g serena-mcp-gateway
14
14
  npx serena-mcp-gateway ./proj-a ./proj-b
15
15
  ```
16
16
 
17
- > **内置依赖自动安装**:首次运行时如果本机缺少 `uvx` 或 `cloudflared`,工具会按当前系统自动选择可用方式安装并立即生效(无需重开终端):
18
- > - **Windows**:自动依次尝试 `winget` → `scoop` → `choco` → 官方 PowerShell 脚本(`uv`)/ GitHub Releases 直下二进制到 `~/.serena-mcp/bin`(`cloudflared`,无需 `winget` 和管理员权限)。
19
- > - **macOS**:自动尝试 `brew` → 官方脚本 / GitHub Releases 直下二进制。
20
- > - **Linux**:自动使用官方脚本 / 静态二进制。
21
- > - 也可单独执行 `serena-mcp --setup` 预先完成环境自检与安装。
17
+ 缺少依赖时,`uv` 可通过系统包管理器安装。需要回退到 astral.sh 的远端安装脚本时,显式传入 `--allow-remote-install` 才会执行。需要自动安装 `cloudflared` 时,下载 Cloudflare 2026.11.2 对应平台的发行文件,核对预置 SHA-256 后再安装到 `~/.serena-mcp/bin`。已安装的 `cloudflared` 继续沿用。Windows ARM64 可先手动准备兼容的 `cloudflared`。
22
18
 
19
+ ### 推荐的本地使用方式
20
+
21
+ ```bash
22
+ serena-mcp --no-tunnel ~/projects/my-app
23
+ ```
24
+
25
+ 传入具体项目目录可使用项目锁定模式;无目录的全局模式允许已授权客户端切换项目。只有远程连接需要 Cloudflare Tunnel。固定令牌请通过环境变量 `MCP_TOKEN` 注入(至少 32 个字符)。未指定时,启动器生成随机令牌并打印一次。
26
+
27
+ OAuth 客户端需要先注册回调地址,并在授权和换取令牌时提交同一个客户端 ID 和回调地址。回调支持 HTTPS 和本机回环 HTTP,PKCE 必须使用 S256。
23
28
  ---
24
29
 
25
30
  ## 二、常用启动方式
@@ -57,7 +62,7 @@ serena-mcp --config ./projects.json
57
62
  ```
58
63
 
59
64
  ### 4. 多项目并行(方式 B:多终端独立运行)
60
- 直接开多个终端分别运行 `serena-mcp <项目A>` 和 `serena-mcp <项目B>` 即可。启动器会自动检测并分配空闲端口,不再出现 `9121 / 9122` 端口冲突。
65
+ 直接开多个终端分别运行 `serena-mcp <项目A>` 和 `serena-mcp <项目B>` 即可。启动器通过本机端口锁协调同一用户下的并发实例,并跳过已占用的端口。
61
66
 
62
67
  ---
63
68
 
@@ -69,7 +74,15 @@ serena-mcp --config ./projects.json
69
74
  | `-p, --port <port>` | 起始本地端口(默认 `9121`,被占用会自动顺延) |
70
75
  | `-t, --token <token>` | 指定固定 Bearer Token(至少 32 位;默认每次随机生成) |
71
76
  | `--context <name>` | 传给 Serena 的 `--context`(默认 `claude-code`) |
77
+ | `--serena-ref <ref>` | 默认使用上游 `v2.1.0` 固定 commit SHA(已缓存时跳过远程 `git fetch`),可指定其他 release tag 或完整 40 位 commit SHA |
78
+ | `--timeout <sec>` | 等待 Serena 就绪的超时秒数(默认 `300`) |
79
+ | `--allow-remote-install` | 允许在需要时下载并执行 astral.sh 的 uv 安装脚本 |
72
80
  | `--no-tunnel` | 仅启动本地 Serena + OAuth 代理,不启动 `cloudflared` |
73
- | `--setup` | 仅检查并自动安装缺失依赖(`uvx` / `cloudflared`),不启动服务 |
81
+ | `--setup` | 仅检查并自动安装缺失依赖(`uvx` / `cloudflared`),可结合 `--no-tunnel` 仅检查本地模式依赖 |
74
82
  | `--no-auto-install` | 缺依赖时仅提示手动命令,不自动安装 |
83
+ | `-v, --version` | 查看版本 |
75
84
  | `-h, --help` | 查看帮助 |
85
+
86
+ 从源码全局安装时,可运行 `./install.sh --no-tunnel` 或 `./install.ps1 --no-tunnel`。安装脚本使用同一套依赖检查,接受 `--no-auto-install` 和 `--allow-remote-install`。
87
+
88
+ > **VPN / TUN 模式提示**:如果开启了 VPN 的 TUN 模式导致 `cloudflared` 无法建立隧道,请在 VPN 规则中将 `cloudflared` 进程或 `*.argotunnel.com`、`*.trycloudflare.com` 设为直连,或改用 `serena-mcp --no-tunnel` 仅启动本地服务。
package/auth-proxy.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { isIP } from 'node:net';
1
2
  import http from 'node:http';
2
3
  import crypto from 'node:crypto';
3
4
  import { URL, pathToFileURL } from 'node:url';
@@ -28,21 +29,24 @@ function escapeHtml(str = '') {
28
29
  .replace(/>/g, '&gt;');
29
30
  }
30
31
 
31
- function getClientKey(req) {
32
- const fwd = req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'];
33
- if (typeof fwd === 'string' && fwd.trim()) {
34
- return fwd.split(',')[0].trim();
35
- }
36
- return req.socket?.remoteAddress || 'unknown';
32
+ const CORS_HEADERS = {
33
+ 'access-control-allow-origin': '*',
34
+ 'access-control-allow-methods': 'GET, POST, DELETE, HEAD, OPTIONS',
35
+ 'access-control-allow-headers': 'Authorization, Content-Type, Mcp-Session-Id, Last-Event-ID, MCP-Protocol-Version',
36
+ 'access-control-expose-headers': 'Mcp-Session-Id, WWW-Authenticate, MCP-Protocol-Version',
37
+ };
38
+
39
+ function getClientKey(req, trustProxy) {
40
+ const ip = trustProxy && req.headers['cf-connecting-ip'];
41
+ return (ip && isIP(ip) ? ip : req.socket.remoteAddress) || 'unknown';
37
42
  }
38
43
 
39
- function getOrigin(req, listenPort) {
40
- const proto = req.headers['x-forwarded-proto'] || 'https';
41
- const host =
42
- req.headers['x-forwarded-host'] ||
43
- req.headers['host'] ||
44
- `127.0.0.1:${listenPort}`;
45
- return `${proto}://${host}`;
44
+ function getOrigin(req, listenPort, trustProxy) {
45
+ const host = req.headers.host;
46
+ if (trustProxy && /^[a-z0-9-]+\.trycloudflare\.com$/i.test(host || '')) {
47
+ return `https://${host.toLowerCase()}`;
48
+ }
49
+ return `http://127.0.0.1:${listenPort}`;
46
50
  }
47
51
 
48
52
  function parseCookies(req) {
@@ -59,7 +63,7 @@ function parseCookies(req) {
59
63
 
60
64
  function readBody(req, maxBytes = 256 * 1024) {
61
65
  return new Promise((resolve, reject) => {
62
- let data = '';
66
+ const chunks = [];
63
67
  let size = 0;
64
68
  req.on('data', (chunk) => {
65
69
  size += chunk.length;
@@ -68,9 +72,9 @@ function readBody(req, maxBytes = 256 * 1024) {
68
72
  reject(new Error('Payload too large'));
69
73
  return;
70
74
  }
71
- data += chunk;
75
+ chunks.push(chunk);
72
76
  });
73
- req.on('end', () => resolve(data));
77
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
74
78
  req.on('error', reject);
75
79
  });
76
80
  }
@@ -81,8 +85,7 @@ function sendJson(res, status, obj, extraHeaders = {}) {
81
85
  'Content-Type': 'application/json',
82
86
  'Cache-Control': 'no-store',
83
87
  'X-Content-Type-Options': 'nosniff',
84
- 'Access-Control-Allow-Origin': '*',
85
- 'Access-Control-Allow-Headers': '*',
88
+ ...CORS_HEADERS,
86
89
  ...extraHeaders,
87
90
  });
88
91
  res.end(JSON.stringify(obj));
@@ -104,7 +107,10 @@ function pruneMap(map, maxSize, now = Date.now()) {
104
107
  function isValidHttpUrl(raw) {
105
108
  try {
106
109
  const parsed = new URL(raw);
107
- return parsed.protocol === 'http:' || parsed.protocol === 'https:';
110
+ return (parsed.protocol === 'https:' ||
111
+ (parsed.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(parsed.hostname))) &&
112
+ !parsed.username && !parsed.password && !raw.includes('#') &&
113
+ raw === raw.trim() && !/[\s\\]/.test(raw);
108
114
  } catch {
109
115
  return false;
110
116
  }
@@ -141,6 +147,7 @@ export function startAuthProxy({
141
147
  listenPort = 9122,
142
148
  masterToken,
143
149
  routes,
150
+ trustProxy = false,
144
151
  }) {
145
152
  if (!masterToken || masterToken.length < 32) {
146
153
  throw new Error('MCP_TOKEN must be at least 32 characters.');
@@ -159,7 +166,7 @@ export function startAuthProxy({
159
166
  const now = Date.now();
160
167
  const rec = failedAttempts.get(clientKey);
161
168
  if (!rec) return false;
162
- if (rec.resetAt <= now) {
169
+ if (rec.expiresAt <= now) {
163
170
  failedAttempts.delete(clientKey);
164
171
  return false;
165
172
  }
@@ -169,34 +176,58 @@ export function startAuthProxy({
169
176
  function recordFailure(clientKey) {
170
177
  const now = Date.now();
171
178
  const rec = failedAttempts.get(clientKey);
172
- if (!rec || rec.resetAt <= now) {
173
- failedAttempts.set(clientKey, { count: 1, resetAt: now + RATE_WINDOW_MS });
179
+ if (!rec || rec.expiresAt <= now) {
180
+ failedAttempts.set(clientKey, { count: 1, expiresAt: now + RATE_WINDOW_MS });
174
181
  } else {
175
182
  rec.count += 1;
176
183
  }
177
- if (failedAttempts.size > 500) {
178
- for (const [k, v] of failedAttempts.entries()) {
179
- if (v.resetAt <= now) failedAttempts.delete(k);
180
- }
181
- }
184
+ pruneMap(failedAttempts, 500, now);
182
185
  }
183
186
 
184
187
  function clearFailures(clientKey) {
185
188
  failedAttempts.delete(clientKey);
186
189
  }
187
190
 
191
+ const registrationRequests = new Map();
192
+ const authorizationRequests = new Map();
193
+
194
+ function allowRequest(buckets, clientKey, limit) {
195
+ const now = Date.now();
196
+ pruneMap(buckets, 500, now);
197
+ const prior = buckets.get(clientKey);
198
+ if (!prior && buckets.size >= 500) return false;
199
+ const timestamps = (prior?.timestamps || []).filter((time) => time > now - RATE_WINDOW_MS);
200
+ if (timestamps.length >= limit) return false;
201
+ timestamps.push(now);
202
+ buckets.set(clientKey, { timestamps, expiresAt: now + RATE_WINDOW_MS });
203
+ return true;
204
+ }
205
+
206
+ function validClient(clientId, redirectUri) {
207
+ const client = registeredClients.get(clientId);
208
+ return client && client.expiresAt > Date.now() && client.redirectUris.includes(redirectUri);
209
+ }
210
+
211
+ function validAuthorization(params) {
212
+ return validClient(params.get('client_id'), params.get('redirect_uri')) &&
213
+ /^[A-Za-z0-9_-]{43}$/.test(params.get('code_challenge') || '') &&
214
+ params.get('code_challenge_method') === 'S256';
215
+ }
216
+
217
+ const grantFields = ['client_id', 'redirect_uri', 'state', 'code_challenge', 'code_challenge_method'];
188
218
  const server = http.createServer(async (req, res) => {
189
- const origin = getOrigin(req, listenPort);
190
- const url = new URL(req.url || '/', origin);
219
+ const origin = getOrigin(req, server.address().port, trustProxy);
220
+ let url;
221
+ try {
222
+ url = new URL(req.url || '/', origin);
223
+ } catch {
224
+ return sendJson(res, 400, { error: 'invalid_request' });
225
+ }
191
226
  const pathname = url.pathname;
192
- const clientKey = getClientKey(req);
227
+ const clientKey = getClientKey(req, trustProxy);
193
228
 
194
229
  if (req.method === 'OPTIONS') {
195
- res.writeHead(204, {
196
- 'Access-Control-Allow-Origin': '*',
197
- 'Access-Control-Allow-Methods': 'GET, POST, DELETE, HEAD, OPTIONS',
198
- 'Access-Control-Allow-Headers': '*',
199
- });
230
+ res.writeHead(204, CORS_HEADERS);
200
231
  res.end();
201
232
  return;
202
233
  }
@@ -226,14 +257,14 @@ export function startAuthProxy({
226
257
  registration_endpoint: `${origin}/oauth/register`,
227
258
  response_types_supported: ['code'],
228
259
  grant_types_supported: ['authorization_code'],
229
- code_challenge_methods_supported: ['S256', 'plain'],
230
- token_endpoint_auth_methods_supported: ['none', 'client_secret_post'],
260
+ code_challenge_methods_supported: ['S256'],
261
+ token_endpoint_auth_methods_supported: ['none'],
231
262
  });
232
263
  }
233
264
 
234
265
  // 3. Dynamic Client Registration (RFC 7591)
235
266
  if (pathname === '/oauth/register' && req.method === 'POST') {
236
- if (isRateLimited(clientKey)) {
267
+ if (isRateLimited(clientKey) || !allowRequest(registrationRequests, clientKey, 10)) {
237
268
  return sendJson(res, 429, { error: 'too_many_requests' });
238
269
  }
239
270
  let body = {};
@@ -243,11 +274,16 @@ export function startAuthProxy({
243
274
  } catch {
244
275
  return sendJson(res, 400, { error: 'invalid_client_metadata' });
245
276
  }
246
- const redirectUris = Array.isArray(body.redirect_uris)
247
- ? body.redirect_uris.filter((u) => typeof u === 'string' && isValidHttpUrl(u))
248
- : [];
249
- const clientId = `mcp-client-${crypto.randomBytes(8).toString('hex')}`;
250
- pruneMap(registeredClients, MAX_CLIENTS - 1);
277
+ const redirectUris = body?.redirect_uris;
278
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0 || redirectUris.length > 20 ||
279
+ !redirectUris.every((uri) => typeof uri === 'string' && uri.length <= 2048 && isValidHttpUrl(uri))) {
280
+ return sendJson(res, 400, { error: 'invalid_redirect_uri' });
281
+ }
282
+ const clientId = `mcp-client-${crypto.randomBytes(16).toString('hex')}`;
283
+ pruneMap(registeredClients, MAX_CLIENTS);
284
+ if (registeredClients.size >= MAX_CLIENTS) {
285
+ return sendJson(res, 429, { error: 'too_many_requests' });
286
+ }
251
287
  registeredClients.set(clientId, {
252
288
  redirectUris,
253
289
  expiresAt: Date.now() + ACCESS_TOKEN_TTL_MS,
@@ -266,9 +302,21 @@ export function startAuthProxy({
266
302
  if (pathname === '/oauth/authorize') {
267
303
  if (req.method === 'GET') {
268
304
  const q = url.searchParams;
305
+ if (!allowRequest(authorizationRequests, clientKey, 20)) {
306
+ return sendJson(res, 429, { error: 'too_many_requests' });
307
+ }
308
+ if (q.get('response_type') !== 'code' || !validAuthorization(q)) {
309
+ return sendJson(res, 400, { error: 'invalid_request' });
310
+ }
269
311
  const csrf = crypto.randomBytes(24).toString('hex');
270
- pruneMap(csrfTokens, MAX_CSRF_TOKENS - 1);
271
- csrfTokens.set(csrf, { expiresAt: Date.now() + CSRF_TTL_MS });
312
+ pruneMap(csrfTokens, MAX_CSRF_TOKENS);
313
+ if (csrfTokens.size >= MAX_CSRF_TOKENS) {
314
+ return sendJson(res, 429, { error: 'too_many_requests' });
315
+ }
316
+ csrfTokens.set(csrf, {
317
+ expiresAt: Date.now() + CSRF_TTL_MS,
318
+ grant: grantFields.map((field) => q.get(field) || ''),
319
+ });
272
320
 
273
321
  const isHttps = origin.startsWith('https://');
274
322
  const cookieFlags = [
@@ -300,13 +348,14 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
300
348
  <body><form method="POST" action="/oauth/authorize">
301
349
  <h3 style="margin:0 0 8px">授权访问本地 Serena MCP</h3>
302
350
  <p style="margin:0;font-size:13px;color:#57606a">粘贴终端打印的本次会话 Token 完成验证:</p>
351
+ <p style="overflow-wrap:anywhere">回调地址:${escapeHtml(q.get('redirect_uri'))}</p>
303
352
  <input type="password" name="token" placeholder="粘贴 MCP Token" required autofocus />
304
353
  <input type="hidden" name="csrf_token" value="${escapeHtml(csrf)}" />
305
354
  <input type="hidden" name="client_id" value="${escapeHtml(q.get('client_id') || '')}" />
306
355
  <input type="hidden" name="redirect_uri" value="${escapeHtml(q.get('redirect_uri') || '')}" />
307
356
  <input type="hidden" name="state" value="${escapeHtml(q.get('state') || '')}" />
308
357
  <input type="hidden" name="code_challenge" value="${escapeHtml(q.get('code_challenge') || '')}" />
309
- <input type="hidden" name="code_challenge_method" value="${escapeHtml(q.get('code_challenge_method') || 'S256')}" />
358
+ <input type="hidden" name="code_challenge_method" value="${escapeHtml(q.get('code_challenge_method'))}" />
310
359
  <button type="submit">确认授权连接</button></form></body></html>`);
311
360
  return;
312
361
  }
@@ -327,22 +376,27 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
327
376
  return;
328
377
  }
329
378
 
330
- // Verify double-submit CSRF token
379
+ if (!validAuthorization(form)) {
380
+ return sendJson(res, 400, { error: 'invalid_request' });
381
+ }
382
+
383
+ // Verify the form matches the request shown to the user.
331
384
  const formCsrf = form.get('csrf_token') || '';
332
385
  const cookieCsrf = parseCookies(req).mcp_csrf || '';
333
386
  const csrfRecord = csrfTokens.get(formCsrf);
334
- csrfTokens.delete(formCsrf);
335
387
  if (
336
388
  !formCsrf ||
337
389
  !csrfRecord ||
338
390
  csrfRecord.expiresAt <= Date.now() ||
339
- !safeEqual(formCsrf, cookieCsrf)
391
+ !safeEqual(formCsrf, cookieCsrf) ||
392
+ grantFields.some((field, index) => (form.get(field) || '') !== csrfRecord.grant[index])
340
393
  ) {
341
394
  res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
342
395
  res.end('授权页面已过期或校验失败,请刷新重试。');
343
396
  return;
344
397
  }
345
398
 
399
+ csrfTokens.delete(formCsrf);
346
400
  const token = (form.get('token') || '').trim();
347
401
  if (!safeEqual(token, masterToken)) {
348
402
  recordFailure(clientKey);
@@ -352,26 +406,8 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
352
406
  }
353
407
  clearFailures(clientKey);
354
408
 
355
- const redirectUriRaw = form.get('redirect_uri') || '';
356
- if (!isValidHttpUrl(redirectUriRaw)) {
357
- res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
358
- res.end('redirect_uri 无效。');
359
- return;
360
- }
361
-
362
- // If client_id was dynamically registered with redirect_uris, enforce strict match
363
- const clientId = form.get('client_id') || '';
364
- if (clientId && registeredClients.has(clientId)) {
365
- const client = registeredClients.get(clientId);
366
- if (
367
- client.redirectUris.length > 0 &&
368
- !client.redirectUris.includes(redirectUriRaw)
369
- ) {
370
- res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
371
- res.end('redirect_uri 与已注册客户端不匹配。');
372
- return;
373
- }
374
- }
409
+ const redirectUriRaw = form.get('redirect_uri');
410
+ const clientId = form.get('client_id');
375
411
 
376
412
  const now = Date.now();
377
413
  pruneMap(authCodes, MAX_AUTH_CODES - 1, now);
@@ -379,7 +415,6 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
379
415
  const code = crypto.randomBytes(24).toString('hex');
380
416
  authCodes.set(code, {
381
417
  codeChallenge: form.get('code_challenge') || '',
382
- method: form.get('code_challenge_method') || 'S256',
383
418
  redirectUri: redirectUriRaw,
384
419
  clientId,
385
420
  expiresAt: now + AUTH_CODE_TTL_MS,
@@ -412,33 +447,23 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
412
447
  const verifier = form.get('code_verifier') || '';
413
448
  const redirectUri = form.get('redirect_uri') || '';
414
449
  const record = authCodes.get(code);
415
- authCodes.delete(code);
416
450
 
417
451
  const now = Date.now();
418
452
  if (!record || record.expiresAt <= now) {
419
453
  recordFailure(clientKey);
420
454
  return sendJson(res, 400, { error: 'invalid_grant' });
421
455
  }
422
- if (redirectUri && redirectUri !== record.redirectUri) {
456
+ const clientId = form.get('client_id');
457
+ const computed = crypto.createHash('sha256').update(verifier).digest('base64url');
458
+ if (form.get('grant_type') !== 'authorization_code' ||
459
+ clientId !== record.clientId || redirectUri !== record.redirectUri ||
460
+ !validClient(clientId, redirectUri) ||
461
+ !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier) ||
462
+ !safeEqual(computed, record.codeChallenge)) {
423
463
  recordFailure(clientKey);
424
- return sendJson(res, 400, {
425
- error: 'invalid_grant',
426
- error_description: 'redirect_uri mismatch',
427
- });
428
- }
429
- if (record.codeChallenge) {
430
- const computed =
431
- record.method === 'S256'
432
- ? crypto.createHash('sha256').update(verifier).digest('base64url')
433
- : verifier;
434
- if (!verifier || !safeEqual(computed, record.codeChallenge)) {
435
- recordFailure(clientKey);
436
- return sendJson(res, 400, {
437
- error: 'invalid_grant',
438
- error_description: 'PKCE failed',
439
- });
440
- }
464
+ return sendJson(res, 400, { error: 'invalid_grant' });
441
465
  }
466
+ authCodes.delete(code);
442
467
 
443
468
  clearFailures(clientKey);
444
469
  pruneMap(accessTokens, MAX_ACCESS_TOKENS - 1, now);
@@ -503,20 +528,28 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
503
528
  }
504
529
 
505
530
  const { route, forwardPath } = matched;
531
+ const headers = { ...req.headers, host: `127.0.0.1:${route.targetPort}` };
532
+ for (const name of [
533
+ 'authorization', 'cookie', 'proxy-authorization', 'connection',
534
+ 'keep-alive', 'upgrade', 'te', 'trailer', 'transfer-encoding',
535
+ ...String(req.headers.connection || '').toLowerCase().split(',').map((value) => value.trim()),
536
+ ]) {
537
+ delete headers[name];
538
+ }
539
+ for (const name of Object.keys(headers)) {
540
+ if (/^(cf-|x-forwarded-|forwarded$)/.test(name)) delete headers[name];
541
+ }
506
542
  const proxyReq = http.request(
507
543
  {
508
544
  hostname: '127.0.0.1',
509
545
  port: route.targetPort,
510
546
  path: forwardPath,
511
547
  method: req.method,
512
- headers: {
513
- ...req.headers,
514
- host: `127.0.0.1:${route.targetPort}`,
515
- },
548
+ headers,
516
549
  },
517
550
  (proxyRes) => {
518
551
  if (!res.headersSent) {
519
- res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);
552
+ res.writeHead(proxyRes.statusCode || 502, { ...proxyRes.headers, ...CORS_HEADERS });
520
553
  }
521
554
  proxyRes.pipe(res);
522
555
  }
package/install.ps1 CHANGED
@@ -1,35 +1,13 @@
1
- $ErrorActionPreference = "Stop"
1
+ $ErrorActionPreference = "Stop"
2
2
 
3
- Write-Host "==> 检查运行环境 (Windows)..." -ForegroundColor Cyan
4
-
5
- if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
6
- Write-Host "[缺少依赖] 请先安装 Node.js (>= 18): winget install --id OpenJS.NodeJS.LTS -e" -ForegroundColor Red
3
+ if (-not (Get-Command node -ErrorAction SilentlyContinue) -or
4
+ -not (Get-Command npm -ErrorAction SilentlyContinue)) {
5
+ Write-Host "[缺少依赖] 请先安装带 npm 的 Node.js (>= 18): https://nodejs.org/"
7
6
  exit 1
8
7
  }
9
8
 
10
- if (-not (Get-Command uvx -ErrorAction SilentlyContinue)) {
11
- if (Get-Command winget -ErrorAction SilentlyContinue) {
12
- Write-Host "==> 正在通过 winget 安装 uv..." -ForegroundColor Yellow
13
- winget install --id astral-sh.uv -e --accept-source-agreements --accept-package-agreements
14
- } else {
15
- Write-Host "[提示] 请手动安装 uv: powershell -ExecutionPolicy ByPass -c `"irm https://astral.sh/uv/install.ps1 | iex`"" -ForegroundColor Yellow
16
- }
17
- }
18
-
19
- if (-not (Get-Command cloudflared -ErrorAction SilentlyContinue)) {
20
- if (Get-Command winget -ErrorAction SilentlyContinue) {
21
- Write-Host "==> 正在通过 winget 安装 cloudflared..." -ForegroundColor Yellow
22
- winget install --id Cloudflare.cloudflared -e --accept-source-agreements --accept-package-agreements
23
- } else {
24
- Write-Host "[提示] 请手动安装 cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/" -ForegroundColor Yellow
25
- }
26
- }
27
-
28
- Write-Host "==> 全局注册 serena-mcp 命令..." -ForegroundColor Cyan
29
- npm install -g $PSScriptRoot
30
-
31
- Write-Host ""
32
- Write-Host "[完成] 请重新打开 PowerShell / CMD 后,在任意目录直接运行:" -ForegroundColor Green
33
- Write-Host " serena-mcp # 全局模式"
34
- Write-Host " serena-mcp . # 当前目录单项目"
35
- Write-Host " serena-mcp D:\code\proj-a D:\code\proj-b # 多项目并行"
9
+ & node (Join-Path $PSScriptRoot "serena-mcp.mjs") @args --setup
10
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
11
+ & npm install -g $PSScriptRoot
12
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
13
+ Write-Host "[完成] 可以用 serena-mcp --no-tunnel . 启动当前项目。"
package/install.sh CHANGED
@@ -2,36 +2,11 @@
2
2
  set -euo pipefail
3
3
 
4
4
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
-
6
- echo "==> 检查运行环境 (macOS / Linux)..."
7
-
8
- if ! command -v node >/dev/null 2>&1; then
9
- echo "[缺少依赖] 请先安装 Node.js (>= 18): https://nodejs.org/"
5
+ if ! command -v node >/dev/null || ! command -v npm >/dev/null; then
6
+ echo "[缺少依赖] 请先安装带 npm 的 Node.js (>= 18): https://nodejs.org/"
10
7
  exit 1
11
8
  fi
12
9
 
13
- if [[ "$(uname -s)" == "Darwin" ]]; then
14
- if ! command -v uvx >/dev/null 2>&1 || ! command -v cloudflared >/dev/null 2>&1; then
15
- if command -v brew >/dev/null 2>&1; then
16
- echo "==> 使用 Homebrew 安装缺失依赖 (uv / cloudflared)..."
17
- command -v uvx >/dev/null 2>&1 || brew install uv
18
- command -v cloudflared >/dev/null 2>&1 || brew install cloudflared
19
- else
20
- echo "[提示] 未检测到 Homebrew,请手动安装 uv 与 cloudflared。"
21
- fi
22
- fi
23
- else
24
- command -v uvx >/dev/null 2>&1 || echo "[提示] 请安装 uv: curl -LsSf https://astral.sh/uv/install.sh | sh"
25
- command -v cloudflared >/dev/null 2>&1 || echo "[提示] 请安装 cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"
26
- fi
27
-
28
- chmod +x "$SCRIPT_DIR/serena-mcp.mjs" "$SCRIPT_DIR/start-serena.sh" "$SCRIPT_DIR/install.sh"
29
-
30
- echo "==> 全局注册 serena-mcp 命令..."
10
+ node "$SCRIPT_DIR/serena-mcp.mjs" "$@" --setup
31
11
  npm install -g "$SCRIPT_DIR"
32
-
33
- echo ""
34
- echo "[完成] 现在可以在任意目录直接运行:"
35
- echo " serena-mcp # 全局模式"
36
- echo " serena-mcp . # 当前目录单项目"
37
- echo " serena-mcp ~/proj-a ~/proj-b # 多项目并行"
12
+ echo '[完成] 可以用 serena-mcp --no-tunnel . 启动当前项目。'
package/installer.mjs CHANGED
@@ -95,11 +95,23 @@ function ensurePrivateBinDir() {
95
95
  }
96
96
  }
97
97
 
98
- async function downloadFile(url, destPath) {
98
+ // SHA-256 values from the upstream 2026.11.2 GitHub release notes.
99
+ const CLOUDFLARED_VERSION = '2026.11.2';
100
+ const CLOUDFLARED_SHA256 = {
101
+ 'cloudflared-windows-386.exe': '272154d4b8a83a2a9bd55502ab27e721838c42772396751eb5a5fc4739c9f23a',
102
+ 'cloudflared-windows-amd64.exe': '555b46c85582461d189cac30d14ad05480d612613801be9f110b8ce08c5b2113',
103
+ 'cloudflared-darwin-amd64.tgz': '870dc2094f98befdd993c455234562be4eee51f8fca6e2e356df4579fa7e6766',
104
+ 'cloudflared-darwin-arm64.tgz': '8654fbdc9057f3e13e95f7892f417f8643113bee1b91ee2388fd0acb05210d55',
105
+ 'cloudflared-linux-amd64': '56f13335143ec0e22772963290683a84a04114a35ec64cbc794a4d39ff9bb8cf',
106
+ 'cloudflared-linux-arm64': '04a7b7f08bce85d56b26ffe1fdbfbb21a074495a363d16f0783c40e25b5c5281',
107
+ 'cloudflared-linux-arm': 'd219494581180764c6d2454409691bb06879d01b43cdeae12476070a7e4e4762',
108
+ 'cloudflared-linux-386': '6bfb8ee3731194223d9a07f4a70f52c203525db5cccccbd55647a0d3c01641b1',
109
+ };
110
+
111
+ async function downloadFile(url, destPath, expectedSha256) {
99
112
  if (!url.startsWith('https://')) {
100
113
  throw new Error(`仅允许通过 HTTPS 下载: ${url}`);
101
114
  }
102
- ensurePrivateBinDir();
103
115
  const res = await fetch(url, {
104
116
  redirect: 'follow',
105
117
  signal: AbortSignal.timeout(60_000),
@@ -107,18 +119,29 @@ async function downloadFile(url, destPath) {
107
119
  if (!res.ok) {
108
120
  throw new Error(`HTTP ${res.status} ${res.statusText}`);
109
121
  }
110
- const buf = Buffer.from(await res.arrayBuffer());
122
+ const chunks = [];
123
+ let size = 0;
124
+ for await (const chunk of res.body) {
125
+ size += chunk.length;
126
+ if (size > MAX_BINARY_BYTES) throw new Error('下载文件超过大小上限');
127
+ chunks.push(chunk);
128
+ }
129
+ const buf = Buffer.concat(chunks, size);
111
130
  if (buf.length < MIN_BINARY_BYTES || buf.length > MAX_BINARY_BYTES) {
112
131
  throw new Error(`下载文件大小异常 (${buf.length} bytes),已中止写入`);
113
132
  }
114
133
  const sha256 = crypto.createHash('sha256').update(buf).digest('hex');
115
- const tmpPath = `${destPath}.tmp-${Date.now()}`;
116
- fs.writeFileSync(tmpPath, buf, { mode: 0o755 });
117
- fs.renameSync(tmpPath, destPath);
118
- console.log(`[Setup] 下载校验完成 SHA-256: ${sha256}`);
134
+ if (sha256 !== expectedSha256) {
135
+ throw new Error('cloudflared SHA-256 与发行版预置校验值不匹配,已中止安装');
136
+ }
137
+ fs.writeFileSync(destPath, buf, { mode: 0o600, flag: 'wx' });
138
+ console.log(`[Setup] SHA-256 校验通过: ${sha256}`);
119
139
  }
120
140
 
121
- async function installUv() {
141
+ async function installUv(allowRemoteInstall) {
142
+ if (!allowRemoteInstall) {
143
+ console.log('[Setup] 远端 uv 安装脚本需要显式授权。如需执行官方脚本,请传入 --allow-remote-install。');
144
+ }
122
145
  if (IS_WIN) {
123
146
  if (commandExists('winget')) {
124
147
  if (
@@ -160,8 +183,8 @@ async function installUv() {
160
183
 
161
184
  // Zero-dependency official PowerShell installer (works without winget or admin)
162
185
  if (
163
- runStep(
164
- '未检测到 winget/scoop,改用官方 PowerShell 脚本安装 uv',
186
+ allowRemoteInstall && runStep(
187
+ '执行来自 astral.sh 的官方 PowerShell 脚本(当前用户权限)',
165
188
  'powershell',
166
189
  [
167
190
  '-NoProfile',
@@ -196,10 +219,10 @@ async function installUv() {
196
219
 
197
220
  // macOS (without brew) / Linux fallback: official shell script
198
221
  if (
199
- runStep(
200
- '通过官方脚本安装 uv',
222
+ allowRemoteInstall && runStep(
223
+ '执行来自 astral.sh 的官方 Shell 脚本(当前用户权限)',
201
224
  'sh',
202
- ['-c', 'curl -LsSf https://astral.sh/uv/install.sh | sh'],
225
+ ['-c', 'script=$(mktemp) || exit 1; trap \'rm -f "$script"\' EXIT; curl --proto "=https" -LsSf https://astral.sh/uv/install.sh -o "$script" && sh "$script"'],
203
226
  { shell: false }
204
227
  )
205
228
  ) {
@@ -210,125 +233,40 @@ async function installUv() {
210
233
  return false;
211
234
  }
212
235
 
213
- async function downloadCloudflaredDirect() {
214
- fs.mkdirSync(LOCAL_BIN_DIR, { recursive: true });
215
-
216
- if (IS_WIN) {
217
- const arch = process.arch === 'ia32' ? '386' : 'amd64';
218
- const url = `https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-${arch}.exe`;
219
- const dest = path.join(LOCAL_BIN_DIR, 'cloudflared.exe');
220
- console.log(`[Setup] 直接下载 cloudflared (${arch}) -> ${dest}`);
221
- await downloadFile(url, dest);
222
- hydratePath();
223
- return commandExists('cloudflared');
224
- }
225
-
226
- if (IS_MAC) {
227
- const arch = process.arch === 'arm64' ? 'arm64' : 'amd64';
228
- const url = `https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-${arch}.tgz`;
229
- const tgzPath = path.join(LOCAL_BIN_DIR, `cloudflared-darwin-${arch}.tgz`);
230
- const dest = path.join(LOCAL_BIN_DIR, 'cloudflared');
231
- console.log(`[Setup] 直接下载 cloudflared (${arch}) -> ${dest}`);
232
- await downloadFile(url, tgzPath);
233
- const extracted = runStep(
234
- '解压 cloudflared',
235
- 'tar',
236
- ['-xzf', tgzPath, '-C', LOCAL_BIN_DIR],
237
- { shell: false }
238
- );
239
- try {
240
- fs.unlinkSync(tgzPath);
241
- } catch {
242
- // ignore
243
- }
244
- if (extracted && fs.existsSync(dest)) {
245
- fs.chmodSync(dest, 0o755);
246
- hydratePath();
247
- return commandExists('cloudflared');
248
- }
249
- return false;
250
- }
251
-
252
- // Linux static binary
253
- const archMap = { x64: 'amd64', arm64: 'arm64', arm: 'arm', ia32: '386' };
254
- const arch = archMap[process.arch] || 'amd64';
255
- const url = `https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${arch}`;
256
- const dest = path.join(LOCAL_BIN_DIR, 'cloudflared');
257
- console.log(`[Setup] 直接下载 cloudflared (${arch}) -> ${dest}`);
258
- await downloadFile(url, dest);
259
- fs.chmodSync(dest, 0o755);
260
- hydratePath();
261
- return commandExists('cloudflared');
262
- }
263
-
264
236
  async function installCloudflared() {
265
- if (IS_WIN) {
266
- if (commandExists('winget')) {
267
- if (
268
- runStep('通过 winget 安装 cloudflared', 'winget', [
269
- 'install',
270
- '--id',
271
- 'Cloudflare.cloudflared',
272
- '-e',
273
- '--accept-source-agreements',
274
- '--accept-package-agreements',
275
- ])
276
- ) {
277
- hydratePath();
278
- if (commandExists('cloudflared')) return true;
279
- }
280
- }
237
+ const arch = { x64: 'amd64', arm64: 'arm64', arm: 'arm', ia32: '386' }[process.arch];
238
+ const suffix = IS_WIN ? '.exe' : IS_MAC ? '.tgz' : '';
239
+ const asset = `cloudflared-${process.platform}-${arch}${suffix}`;
240
+ const expectedSha256 = CLOUDFLARED_SHA256[asset];
241
+ if (!expectedSha256) throw new Error(`此平台没有已校验的 cloudflared 安装包: ${asset}`);
281
242
 
282
- if (commandExists('scoop', { useShell: true })) {
283
- if (
284
- runStep('通过 scoop 安装 cloudflared', 'scoop', [
285
- 'install',
286
- 'cloudflared',
287
- ], { shell: true })
288
- ) {
289
- hydratePath();
290
- if (commandExists('cloudflared')) return true;
291
- }
292
- }
293
-
294
- if (commandExists('choco', { useShell: true })) {
295
- if (
296
- runStep('通过 choco 安装 cloudflared', 'choco', [
297
- 'install',
298
- 'cloudflared',
299
- '-y',
300
- ], { shell: true })
301
- ) {
302
- hydratePath();
303
- if (commandExists('cloudflared')) return true;
304
- }
243
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'serena-cloudflared-'));
244
+ try {
245
+ const downloaded = path.join(tempDir, asset);
246
+ const url = `https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/${asset}`;
247
+ await downloadFile(url, downloaded, expectedSha256);
248
+ if (IS_MAC && !runStep('解压已校验的 cloudflared', 'tar',
249
+ ['-xzf', downloaded, '-C', tempDir, 'cloudflared'])) {
250
+ throw new Error('无法解压 cloudflared');
305
251
  }
252
+ const source = IS_MAC ? path.join(tempDir, 'cloudflared') : downloaded;
253
+ if (!fs.lstatSync(source).isFile()) throw new Error('无效的 cloudflared 文件');
306
254
 
255
+ ensurePrivateBinDir();
256
+ const executable = IS_WIN ? 'cloudflared.exe' : 'cloudflared';
257
+ const stagingDir = fs.mkdtempSync(path.join(LOCAL_BIN_DIR, '.install-'));
307
258
  try {
308
- return await downloadCloudflaredDirect();
309
- } catch (err) {
310
- console.error(`[Setup] 直接下载 cloudflared 失败: ${err.message}`);
311
- return false;
259
+ const staged = path.join(stagingDir, executable);
260
+ fs.copyFileSync(source, staged, fs.constants.COPYFILE_EXCL);
261
+ fs.chmodSync(staged, 0o755);
262
+ fs.renameSync(staged, path.join(LOCAL_BIN_DIR, executable));
263
+ } finally {
264
+ fs.rmSync(stagingDir, { recursive: true, force: true });
312
265
  }
313
- }
314
-
315
- if (IS_MAC && commandExists('brew')) {
316
- if (
317
- runStep('通过 Homebrew 安装 cloudflared', 'brew', [
318
- 'install',
319
- 'cloudflared',
320
- ])
321
- ) {
322
- hydratePath();
323
- if (commandExists('cloudflared')) return true;
324
- }
325
- }
326
-
327
- try {
328
- return await downloadCloudflaredDirect();
329
- } catch (err) {
330
- console.error(`[Setup] 直接下载 cloudflared 失败: ${err.message}`);
331
- return false;
266
+ hydratePath();
267
+ return commandExists('cloudflared');
268
+ } finally {
269
+ fs.rmSync(tempDir, { recursive: true, force: true });
332
270
  }
333
271
  }
334
272
 
@@ -372,6 +310,7 @@ function printManualGuide(missing) {
372
310
  export async function ensureDependencies({
373
311
  needTunnel = true,
374
312
  autoInstall = true,
313
+ allowRemoteInstall = false,
375
314
  } = {}) {
376
315
  hydratePath();
377
316
 
@@ -395,7 +334,7 @@ export async function ensureDependencies({
395
334
  );
396
335
 
397
336
  if (missing.includes('uvx')) {
398
- const ok = await installUv();
337
+ const ok = await installUv(allowRemoteInstall);
399
338
  if (ok) {
400
339
  console.log('[Setup] uv / uvx 安装成功!');
401
340
  } else {
@@ -404,11 +343,16 @@ export async function ensureDependencies({
404
343
  }
405
344
 
406
345
  if (missing.includes('cloudflared')) {
407
- const ok = await installCloudflared();
408
- if (ok) {
409
- console.log('[Setup] cloudflared 安装成功!');
410
- } else {
411
- console.error('[Setup] cloudflared 自动安装失败。');
346
+ try {
347
+ const ok = await installCloudflared();
348
+ if (ok) {
349
+ console.log('[Setup] cloudflared 安装成功!');
350
+ } else {
351
+ console.error('[Setup] cloudflared 自动安装失败。');
352
+ }
353
+ } catch (error) {
354
+ console.error(`[Setup] cloudflared 自动安装失败: ${error.message}`);
355
+ console.error('[Hint] 若仅在本机使用,可改用 --no-tunnel 跳过 cloudflared。');
412
356
  }
413
357
  }
414
358
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serena-mcp-gateway",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "Cross-platform Serena MCP launcher with OAuth 2.1 proxy, Cloudflare Tunnel, and multi-project parallel routing",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -31,5 +31,16 @@
31
31
  ],
32
32
  "publishConfig": {
33
33
  "access": "public"
34
+ },
35
+ "scripts": {
36
+ "test": "node --test"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/Birdyqaq/serena-mcp-gateway.git"
41
+ },
42
+ "homepage": "https://github.com/Birdyqaq/serena-mcp-gateway#readme",
43
+ "bugs": {
44
+ "url": "https://github.com/Birdyqaq/serena-mcp-gateway/issues"
34
45
  }
35
46
  }
package/serena-mcp.mjs CHANGED
@@ -9,6 +9,9 @@ import { spawn, spawnSync } from 'node:child_process';
9
9
  import { startAuthProxy } from './auth-proxy.mjs';
10
10
  import { ensureDependencies, hydratePath } from './installer.mjs';
11
11
 
12
+ // Pinned commit SHA for Serena v2.1.0 so uvx skips remote `git fetch` on cached runs.
13
+ const DEFAULT_SERENA_REF = '5e4f5cd173c7ff3eed37ee3f1de6c266b937c5dc';
14
+ const DEFAULT_STARTUP_TIMEOUT_SEC = 300;
12
15
  const IS_WIN = process.platform === 'win32';
13
16
  const PKG_VERSION = JSON.parse(
14
17
  fs.readFileSync(
@@ -32,6 +35,9 @@ Serena MCP Gateway (跨平台单项目 / 多项目并行启动器)
32
35
  -c, --config <path> 项目配置 JSON(支持数组或 {"别名": "路径"} 对象)
33
36
  -p, --port <number> 起始本地端口(默认 9121,冲突时自动顺延,支持多终端并行)
34
37
  -t, --token <token> 自定义 Bearer Token(>=32 字符;默认每次随机生成)
38
+ --serena-ref <ref> Serena release tag 或完整 40 位 commit SHA(默认 v2.1.0 固定 SHA)
39
+ --timeout <sec> 等待 Serena 就绪的超时秒数(默认 300)
40
+ --allow-remote-install 允许执行 uv 官方远端安装脚本
35
41
  --context <name> 传给 Serena 的 --context(默认 claude-code)
36
42
  --no-tunnel 仅启动本地 Serena + OAuth 代理,不启动 cloudflared
37
43
  --setup 仅检查并自动安装缺失依赖(uvx / cloudflared),不启动服务
@@ -116,6 +122,9 @@ function parseArgs(argv) {
116
122
  const opts = {
117
123
  basePort: 9121,
118
124
  token: process.env.MCP_TOKEN || '',
125
+ serenaRef: DEFAULT_SERENA_REF,
126
+ startupTimeoutSec: DEFAULT_STARTUP_TIMEOUT_SEC,
127
+ allowRemoteInstall: false,
119
128
  context: 'claude-code',
120
129
  noTunnel: false,
121
130
  setup: false,
@@ -125,6 +134,11 @@ function parseArgs(argv) {
125
134
  projects: [],
126
135
  };
127
136
 
137
+ function readValue(flag, value) {
138
+ if (!value || value.startsWith('-')) throw new Error(`${flag} 需要指定参数值`);
139
+ return value;
140
+ }
141
+
128
142
  for (let i = 0; i < argv.length; i++) {
129
143
  const arg = argv[i];
130
144
  if (arg === '-h' || arg === '--help') {
@@ -138,18 +152,31 @@ function parseArgs(argv) {
138
152
  } else if (arg === '--no-auto-install') {
139
153
  opts.noAutoInstall = true;
140
154
  } else if (arg === '-p' || arg === '--port') {
141
- const val = Number(argv[++i]);
155
+ const val = Number(readValue(arg, argv[++i]));
142
156
  if (!Number.isInteger(val) || val < 1024 || val > 65535) {
143
157
  throw new Error(`无效端口号: ${argv[i]}`);
144
158
  }
145
159
  opts.basePort = val;
146
160
  } else if (arg === '-t' || arg === '--token') {
147
- opts.token = argv[++i] || '';
161
+ opts.token = readValue(arg, argv[++i]);
162
+ console.warn('[Security] 命令行 Token 可能出现在历史记录或进程列表中,建议使用 MCP_TOKEN 环境变量。');
148
163
  } else if (arg === '--context') {
149
- opts.context = argv[++i] || 'claude-code';
164
+ opts.context = readValue(arg, argv[++i]);
165
+ } else if (arg === '--allow-remote-install') {
166
+ opts.allowRemoteInstall = true;
167
+ } else if (arg === '--timeout') {
168
+ const val = Number(readValue(arg, argv[++i]));
169
+ if (!Number.isInteger(val) || val < 10 || val > 3600) {
170
+ throw new Error(`无效超时时间(需 10~3600 秒): ${argv[i]}`);
171
+ }
172
+ opts.startupTimeoutSec = val;
173
+ } else if (arg === '--serena-ref') {
174
+ opts.serenaRef = readValue(arg, argv[++i]);
175
+ if (!/^(?:[0-9a-f]{40}|v[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?)$/i.test(opts.serenaRef)) {
176
+ throw new Error('--serena-ref 需要 release tag 或完整 40 位 commit SHA');
177
+ }
150
178
  } else if (arg === '-c' || arg === '--config') {
151
- const cfgPath = argv[++i];
152
- if (!cfgPath) throw new Error('--config 需要指定 JSON 文件路径');
179
+ const cfgPath = readValue(arg, argv[++i]);
153
180
  opts.projects.push(...loadConfigProjects(cfgPath));
154
181
  } else if (arg.startsWith('-')) {
155
182
  throw new Error(`未知参数: ${arg}(使用 --help 查看用法)`);
@@ -158,14 +185,13 @@ function parseArgs(argv) {
158
185
  }
159
186
  }
160
187
 
161
- // Deduplicate slugs when multiple projects share the same folder name
162
- const slugCount = new Map();
163
- for (const proj of opts.projects) {
164
- const count = slugCount.get(proj.slug) || 0;
165
- slugCount.set(proj.slug, count + 1);
166
- if (count > 0) {
167
- proj.slug = `${proj.slug}-${count + 1}`;
188
+ const usedSlugs = new Set();
189
+ for (const project of opts.projects) {
190
+ const base = project.slug;
191
+ for (let suffix = 2; usedSlugs.has(project.slug); suffix++) {
192
+ project.slug = `${base}-${suffix}`;
168
193
  }
194
+ usedSlugs.add(project.slug);
169
195
  }
170
196
 
171
197
  return opts;
@@ -182,46 +208,88 @@ function isPortFree(port) {
182
208
  });
183
209
  }
184
210
 
185
- async function allocateFreePort(startPort, reserved) {
186
- let port = startPort;
187
- while (port < 65535) {
188
- if (!reserved.has(port) && (await isPortFree(port))) {
189
- reserved.add(port);
190
- return port;
211
+ const portLockDir = path.join(os.homedir(), '.serena-mcp', 'ports');
212
+
213
+ async function allocateFreePort(startPort, locks) {
214
+ fs.mkdirSync(portLockDir, { recursive: true, mode: 0o700 });
215
+ for (let port = startPort; port <= 65535; port++) {
216
+ const lock = path.join(portLockDir, String(port));
217
+ try {
218
+ fs.mkdirSync(lock, { mode: 0o700 });
219
+ } catch (error) {
220
+ if (error.code === 'EEXIST') continue;
221
+ throw error;
191
222
  }
192
- port++;
223
+ locks.set(port, lock);
224
+ if (await isPortFree(port)) return port;
225
+ releasePort(port, locks);
193
226
  }
194
227
  throw new Error('无法找到可用的本地端口');
195
228
  }
196
229
 
197
- function waitForPort(port, label, child, timeoutMs = 120_000) {
230
+ function releasePort(port, locks) {
231
+ const lock = locks.get(port);
232
+ if (lock) {
233
+ fs.rmdirSync(lock);
234
+ locks.delete(port);
235
+ }
236
+ }
237
+
238
+ function waitForPort(port, label, child, timeoutMs = DEFAULT_STARTUP_TIMEOUT_SEC * 1000) {
198
239
  const start = Date.now();
199
240
  return new Promise((resolve, reject) => {
200
241
  let settled = false;
242
+ const hintTimer = setTimeout(() => {
243
+ if (!settled) {
244
+ console.log(
245
+ `[Wait] 仍在等待 Serena [${label}] 就绪(若首次运行正在下载依赖,可能需要 1~3 分钟)...`
246
+ );
247
+ }
248
+ }, 15_000);
249
+
250
+ const cleanup = () => {
251
+ clearTimeout(hintTimer);
252
+ child.off('exit', onExit);
253
+ child.off('error', onError);
254
+ };
201
255
 
202
256
  const onExit = (code) => {
203
257
  if (!settled) {
204
258
  settled = true;
259
+ cleanup();
205
260
  reject(new Error(`Serena [${label}] 在就绪前意外退出 (code=${code})`));
206
261
  }
207
262
  };
263
+ const onError = (error) => {
264
+ settled = true;
265
+ cleanup();
266
+ reject(error);
267
+ };
208
268
  child.once('exit', onExit);
269
+ child.once('error', onError);
209
270
 
210
271
  const probe = () => {
211
272
  if (settled) return;
212
273
  const socket = net.createConnection({ host: '127.0.0.1', port });
213
274
  socket.once('connect', () => {
214
275
  socket.destroy();
276
+ if (settled) return;
215
277
  settled = true;
216
- child.off('exit', onExit);
278
+ cleanup();
217
279
  resolve();
218
280
  });
219
281
  socket.once('error', () => {
220
282
  socket.destroy();
283
+ if (settled) return;
221
284
  if (Date.now() - start >= timeoutMs) {
222
285
  settled = true;
223
- child.off('exit', onExit);
224
- reject(new Error(`等待 Serena [${label}] (端口 ${port}) 就绪超时`));
286
+ cleanup();
287
+ reject(
288
+ new Error(
289
+ `等待 Serena [${label}] (端口 ${port}) 就绪超时(${Math.round(timeoutMs / 1000)}s)。` +
290
+ '若开了 VPN TUN 模式或首次拉取较慢,可尝试关闭 TUN、使用 --timeout 600 或 --no-tunnel。'
291
+ )
292
+ );
225
293
  return;
226
294
  }
227
295
  setTimeout(probe, 500);
@@ -251,18 +319,23 @@ function pipePrefixed(stream, prefix, target = process.stdout) {
251
319
  });
252
320
  }
253
321
 
254
- function killProcessTree(child) {
255
- if (!child || child.killed || !child.pid) return;
322
+ async function killProcessTree(child) {
323
+ if (!child.pid) return;
324
+ if (IS_WIN) {
325
+ spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore' });
326
+ return;
327
+ }
328
+
329
+ const group = -child.pid;
256
330
  try {
257
- if (IS_WIN) {
258
- spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
259
- stdio: 'ignore',
260
- });
261
- } else {
262
- child.kill('SIGTERM');
331
+ process.kill(group, 'SIGTERM');
332
+ for (let attempt = 0; attempt < 15; attempt++) {
333
+ await new Promise((resolve) => setTimeout(resolve, 100));
334
+ process.kill(group, 0);
263
335
  }
264
- } catch {
265
- // ignore already-exited processes
336
+ process.kill(group, 'SIGKILL');
337
+ } catch (error) {
338
+ if (error.code !== 'ESRCH') console.error(`[Shutdown] ${error.message}`);
266
339
  }
267
340
  }
268
341
 
@@ -288,14 +361,19 @@ async function main() {
288
361
  hydratePath();
289
362
 
290
363
  if (opts.setup) {
291
- await ensureDependencies({ needTunnel: true, autoInstall: true });
292
- console.log('\n[OK] 环境依赖检查完成,uvx 与 cloudflared 均已就绪!');
364
+ await ensureDependencies({
365
+ needTunnel: !opts.noTunnel,
366
+ autoInstall: !opts.noAutoInstall,
367
+ allowRemoteInstall: opts.allowRemoteInstall,
368
+ });
369
+ console.log('\n[OK] 所需依赖均已就绪。');
293
370
  process.exit(0);
294
371
  }
295
372
 
296
373
  await ensureDependencies({
297
374
  needTunnel: !opts.noTunnel,
298
375
  autoInstall: !opts.noAutoInstall,
376
+ allowRemoteInstall: opts.allowRemoteInstall,
299
377
  });
300
378
 
301
379
  const token = opts.token || crypto.randomBytes(24).toString('hex');
@@ -305,10 +383,13 @@ async function main() {
305
383
  }
306
384
 
307
385
  const children = [];
386
+ const portLocks = new Map();
387
+ const childEnv = { ...process.env };
388
+ delete childEnv.MCP_TOKEN;
308
389
  let proxyServer = null;
309
390
  let shuttingDown = false;
310
391
 
311
- const shutdown = (exitCode = 0) => {
392
+ const shutdown = async (exitCode = 0) => {
312
393
  if (shuttingDown) return;
313
394
  shuttingDown = true;
314
395
  console.log('\n[Shutdown] 正在停止所有 Serena 实例与隧道...');
@@ -319,16 +400,16 @@ async function main() {
319
400
  // ignore
320
401
  }
321
402
  }
322
- for (const child of children) {
323
- killProcessTree(child);
324
- }
325
- setTimeout(() => process.exit(exitCode), 300);
403
+ await Promise.all(children.map(killProcessTree));
404
+ process.exit(exitCode);
326
405
  };
327
406
 
328
407
  process.on('SIGINT', () => shutdown(0));
329
408
  process.on('SIGTERM', () => shutdown(0));
330
409
 
331
- const reservedPorts = new Set();
410
+ process.on('exit', () => {
411
+ for (const port of portLocks.keys()) releasePort(port, portLocks);
412
+ });
332
413
  const isMultiProject = opts.projects.length > 1;
333
414
  const targets =
334
415
  opts.projects.length === 0
@@ -336,12 +417,8 @@ async function main() {
336
417
  : opts.projects;
337
418
 
338
419
  const routes = [];
339
- const startupPromises = [];
340
420
 
341
- console.log('==================================================');
342
- console.log('本次会话 Bearer Token:');
343
- console.log(token);
344
- console.log('==================================================');
421
+ if (!opts.token) console.log(`本次会话 Bearer Token: ${token}`);
345
422
 
346
423
  if (opts.projects.length === 0) {
347
424
  console.log('[Mode] 全局多项目模式(可在对话中随时指定/切换项目路径)');
@@ -352,19 +429,15 @@ async function main() {
352
429
  console.log(`[Mode] 多项目并行模式(共 ${opts.projects.length} 个项目同时启动)`);
353
430
  }
354
431
 
355
- for (const target of targets) {
356
- const port = await allocateFreePort(opts.basePort, reservedPorts);
432
+ async function startTarget(target) {
433
+ if (shuttingDown) return;
434
+ const port = await allocateFreePort(opts.basePort, portLocks);
435
+ if (shuttingDown) return;
357
436
  const prefix = isMultiProject ? `/p/${target.slug}` : '';
358
- routes.push({
359
- prefix,
360
- targetPort: port,
361
- name: target.name,
362
- projectPath: target.projectPath,
363
- });
364
437
 
365
438
  const serenaArgs = [
366
439
  '--from',
367
- 'git+https://github.com/oraios/serena',
440
+ `git+https://github.com/oraios/serena@${opts.serenaRef}`,
368
441
  'serena',
369
442
  'start-mcp-server',
370
443
  '--context',
@@ -389,35 +462,54 @@ async function main() {
389
462
  const child = spawn('uvx', serenaArgs, {
390
463
  stdio: ['ignore', 'pipe', 'pipe'],
391
464
  shell: false,
465
+ detached: !IS_WIN,
466
+ env: childEnv,
392
467
  });
393
468
  children.push(child);
394
469
 
395
470
  pipePrefixed(child.stdout, `[serena:${target.name}]`, process.stdout);
396
471
  pipePrefixed(child.stderr, `[serena:${target.name}]`, process.stderr);
397
472
 
398
- startupPromises.push(waitForPort(port, target.name, child));
473
+ await waitForPort(port, target.name, child, opts.startupTimeoutSec * 1000);
474
+ child.on('exit', (code, signal) => {
475
+ if (shuttingDown) return;
476
+ console.error(`[Error] Serena [${target.name}] 已退出 (code=${code}, signal=${signal})`);
477
+ void shutdown(1);
478
+ });
479
+ return { prefix, targetPort: port, name: target.name, projectPath: target.projectPath };
399
480
  }
400
481
 
401
- console.log('[Wait] 等待所有 Serena 实例就绪(首次运行可能需要下载依赖)...');
482
+ let proxyPort;
402
483
  try {
403
- await Promise.all(startupPromises);
484
+ console.log('[Wait] 等待所有 Serena 实例就绪(首次运行可能需要下载依赖)...');
485
+ routes.push(...await Promise.all(targets.map(startTarget)));
486
+ if (shuttingDown) return;
487
+
488
+ for (let attempt = 0; attempt < 5; attempt++) {
489
+ proxyPort = await allocateFreePort(Math.min(opts.basePort + 1, 65535), portLocks);
490
+ if (shuttingDown) return;
491
+ try {
492
+ proxyServer = await startAuthProxy({
493
+ listenPort: proxyPort,
494
+ masterToken: token,
495
+ routes,
496
+ trustProxy: !opts.noTunnel,
497
+ });
498
+ break;
499
+ } catch (error) {
500
+ releasePort(proxyPort, portLocks);
501
+ if (error.code !== 'EADDRINUSE' || attempt === 4) throw error;
502
+ }
503
+ }
404
504
  } catch (err) {
405
505
  console.error(`[Error] ${err.message}`);
406
- shutdown(1);
506
+ await shutdown(1);
407
507
  return;
408
508
  }
409
509
 
410
- const proxyPort = await allocateFreePort(opts.basePort + 1, reservedPorts);
411
- proxyServer = await startAuthProxy({
412
- listenPort: proxyPort,
413
- masterToken: token,
414
- routes,
415
- });
416
-
417
510
  const printEndpoints = (baseUrl) => {
418
511
  console.log('\n==================================================');
419
512
  console.log('Serena MCP 已就绪,复制以下地址到客户端:');
420
- console.log(`Bearer Token: ${token}`);
421
513
  console.log('--------------------------------------------------');
422
514
  for (const r of routes) {
423
515
  const endpoint = `${baseUrl}${r.prefix}/mcp`;
@@ -440,6 +532,8 @@ async function main() {
440
532
  {
441
533
  stdio: ['ignore', 'pipe', 'pipe'],
442
534
  shell: false,
535
+ detached: !IS_WIN,
536
+ env: childEnv,
443
537
  }
444
538
  );
445
539
  children.push(cf);
@@ -459,9 +553,18 @@ async function main() {
459
553
 
460
554
  cf.stdout.on('data', watchTunnelUrl);
461
555
  cf.stderr.on('data', watchTunnelUrl);
556
+ cf.on('error', (error) => {
557
+ console.error(`[Error] cloudflared 启动失败: ${error.message}`);
558
+ void shutdown(1);
559
+ });
462
560
  cf.on('exit', (code) => {
463
561
  if (!shuttingDown) {
464
562
  console.error(`[Error] cloudflared 已退出 (code=${code})`);
563
+ if (!printedUrl) {
564
+ console.error(
565
+ '[Hint] Cloudflare Tunnel 未能建立连接。若开启了 VPN TUN 模式,请将 cloudflared 或 *.argotunnel.com 设为直连,或使用 --no-tunnel 仅启动本地服务。'
566
+ );
567
+ }
465
568
  shutdown(code || 1);
466
569
  }
467
570
  });