serena-mcp-gateway 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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,12 @@ 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`,可指定其他 release tag 或完整 40 位 commit SHA |
78
+ | `--allow-remote-install` | 允许在需要时下载并执行 astral.sh 的 uv 安装脚本 |
72
79
  | `--no-tunnel` | 仅启动本地 Serena + OAuth 代理,不启动 `cloudflared` |
73
- | `--setup` | 仅检查并自动安装缺失依赖(`uvx` / `cloudflared`),不启动服务 |
80
+ | `--setup` | 仅检查并自动安装缺失依赖(`uvx` / `cloudflared`),可结合 `--no-tunnel` 仅检查本地模式依赖 |
74
81
  | `--no-auto-install` | 缺依赖时仅提示手动命令,不自动安装 |
82
+ | `-v, --version` | 查看版本 |
75
83
  | `-h, --help` | 查看帮助 |
84
+
85
+ 从源码全局安装时,可运行 `./install.sh --no-tunnel` 或 `./install.ps1 --no-tunnel`。安装脚本使用同一套依赖检查,接受 `--no-auto-install` 和 `--allow-remote-install`。
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
- }
281
-
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
- }
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}`);
293
242
 
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;
312
- }
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;
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 });
324
265
  }
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 {
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.0",
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,7 @@ 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
+ const DEFAULT_SERENA_REF = 'v2.1.0';
12
13
  const IS_WIN = process.platform === 'win32';
13
14
  const PKG_VERSION = JSON.parse(
14
15
  fs.readFileSync(
@@ -32,6 +33,8 @@ Serena MCP Gateway (跨平台单项目 / 多项目并行启动器)
32
33
  -c, --config <path> 项目配置 JSON(支持数组或 {"别名": "路径"} 对象)
33
34
  -p, --port <number> 起始本地端口(默认 9121,冲突时自动顺延,支持多终端并行)
34
35
  -t, --token <token> 自定义 Bearer Token(>=32 字符;默认每次随机生成)
36
+ --serena-ref <ref> Serena release tag 或完整 40 位 commit SHA(默认 v2.1.0)
37
+ --allow-remote-install 允许执行 uv 官方远端安装脚本
35
38
  --context <name> 传给 Serena 的 --context(默认 claude-code)
36
39
  --no-tunnel 仅启动本地 Serena + OAuth 代理,不启动 cloudflared
37
40
  --setup 仅检查并自动安装缺失依赖(uvx / cloudflared),不启动服务
@@ -116,6 +119,8 @@ function parseArgs(argv) {
116
119
  const opts = {
117
120
  basePort: 9121,
118
121
  token: process.env.MCP_TOKEN || '',
122
+ serenaRef: DEFAULT_SERENA_REF,
123
+ allowRemoteInstall: false,
119
124
  context: 'claude-code',
120
125
  noTunnel: false,
121
126
  setup: false,
@@ -125,6 +130,11 @@ function parseArgs(argv) {
125
130
  projects: [],
126
131
  };
127
132
 
133
+ function readValue(flag, value) {
134
+ if (!value || value.startsWith('-')) throw new Error(`${flag} 需要指定参数值`);
135
+ return value;
136
+ }
137
+
128
138
  for (let i = 0; i < argv.length; i++) {
129
139
  const arg = argv[i];
130
140
  if (arg === '-h' || arg === '--help') {
@@ -138,18 +148,25 @@ function parseArgs(argv) {
138
148
  } else if (arg === '--no-auto-install') {
139
149
  opts.noAutoInstall = true;
140
150
  } else if (arg === '-p' || arg === '--port') {
141
- const val = Number(argv[++i]);
151
+ const val = Number(readValue(arg, argv[++i]));
142
152
  if (!Number.isInteger(val) || val < 1024 || val > 65535) {
143
153
  throw new Error(`无效端口号: ${argv[i]}`);
144
154
  }
145
155
  opts.basePort = val;
146
156
  } else if (arg === '-t' || arg === '--token') {
147
- opts.token = argv[++i] || '';
157
+ opts.token = readValue(arg, argv[++i]);
158
+ console.warn('[Security] 命令行 Token 可能出现在历史记录或进程列表中,建议使用 MCP_TOKEN 环境变量。');
148
159
  } else if (arg === '--context') {
149
- opts.context = argv[++i] || 'claude-code';
160
+ opts.context = readValue(arg, argv[++i]);
161
+ } else if (arg === '--allow-remote-install') {
162
+ opts.allowRemoteInstall = true;
163
+ } else if (arg === '--serena-ref') {
164
+ opts.serenaRef = readValue(arg, argv[++i]);
165
+ if (!/^(?:[0-9a-f]{40}|v[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?)$/i.test(opts.serenaRef)) {
166
+ throw new Error('--serena-ref 需要 release tag 或完整 40 位 commit SHA');
167
+ }
150
168
  } else if (arg === '-c' || arg === '--config') {
151
- const cfgPath = argv[++i];
152
- if (!cfgPath) throw new Error('--config 需要指定 JSON 文件路径');
169
+ const cfgPath = readValue(arg, argv[++i]);
153
170
  opts.projects.push(...loadConfigProjects(cfgPath));
154
171
  } else if (arg.startsWith('-')) {
155
172
  throw new Error(`未知参数: ${arg}(使用 --help 查看用法)`);
@@ -158,14 +175,13 @@ function parseArgs(argv) {
158
175
  }
159
176
  }
160
177
 
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}`;
178
+ const usedSlugs = new Set();
179
+ for (const project of opts.projects) {
180
+ const base = project.slug;
181
+ for (let suffix = 2; usedSlugs.has(project.slug); suffix++) {
182
+ project.slug = `${base}-${suffix}`;
168
183
  }
184
+ usedSlugs.add(project.slug);
169
185
  }
170
186
 
171
187
  return opts;
@@ -182,18 +198,33 @@ function isPortFree(port) {
182
198
  });
183
199
  }
184
200
 
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;
201
+ const portLockDir = path.join(os.homedir(), '.serena-mcp', 'ports');
202
+
203
+ async function allocateFreePort(startPort, locks) {
204
+ fs.mkdirSync(portLockDir, { recursive: true, mode: 0o700 });
205
+ for (let port = startPort; port <= 65535; port++) {
206
+ const lock = path.join(portLockDir, String(port));
207
+ try {
208
+ fs.mkdirSync(lock, { mode: 0o700 });
209
+ } catch (error) {
210
+ if (error.code === 'EEXIST') continue;
211
+ throw error;
191
212
  }
192
- port++;
213
+ locks.set(port, lock);
214
+ if (await isPortFree(port)) return port;
215
+ releasePort(port, locks);
193
216
  }
194
217
  throw new Error('无法找到可用的本地端口');
195
218
  }
196
219
 
220
+ function releasePort(port, locks) {
221
+ const lock = locks.get(port);
222
+ if (lock) {
223
+ fs.rmdirSync(lock);
224
+ locks.delete(port);
225
+ }
226
+ }
227
+
197
228
  function waitForPort(port, label, child, timeoutMs = 120_000) {
198
229
  const start = Date.now();
199
230
  return new Promise((resolve, reject) => {
@@ -205,22 +236,32 @@ function waitForPort(port, label, child, timeoutMs = 120_000) {
205
236
  reject(new Error(`Serena [${label}] 在就绪前意外退出 (code=${code})`));
206
237
  }
207
238
  };
239
+ const onError = (error) => {
240
+ settled = true;
241
+ child.off('exit', onExit);
242
+ reject(error);
243
+ };
208
244
  child.once('exit', onExit);
245
+ child.once('error', onError);
209
246
 
210
247
  const probe = () => {
211
248
  if (settled) return;
212
249
  const socket = net.createConnection({ host: '127.0.0.1', port });
213
250
  socket.once('connect', () => {
214
251
  socket.destroy();
252
+ if (settled) return;
215
253
  settled = true;
216
254
  child.off('exit', onExit);
255
+ child.off('error', onError);
217
256
  resolve();
218
257
  });
219
258
  socket.once('error', () => {
220
259
  socket.destroy();
260
+ if (settled) return;
221
261
  if (Date.now() - start >= timeoutMs) {
222
262
  settled = true;
223
263
  child.off('exit', onExit);
264
+ child.off('error', onError);
224
265
  reject(new Error(`等待 Serena [${label}] (端口 ${port}) 就绪超时`));
225
266
  return;
226
267
  }
@@ -251,18 +292,23 @@ function pipePrefixed(stream, prefix, target = process.stdout) {
251
292
  });
252
293
  }
253
294
 
254
- function killProcessTree(child) {
255
- if (!child || child.killed || !child.pid) return;
295
+ async function killProcessTree(child) {
296
+ if (!child.pid) return;
297
+ if (IS_WIN) {
298
+ spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore' });
299
+ return;
300
+ }
301
+
302
+ const group = -child.pid;
256
303
  try {
257
- if (IS_WIN) {
258
- spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
259
- stdio: 'ignore',
260
- });
261
- } else {
262
- child.kill('SIGTERM');
304
+ process.kill(group, 'SIGTERM');
305
+ for (let attempt = 0; attempt < 15; attempt++) {
306
+ await new Promise((resolve) => setTimeout(resolve, 100));
307
+ process.kill(group, 0);
263
308
  }
264
- } catch {
265
- // ignore already-exited processes
309
+ process.kill(group, 'SIGKILL');
310
+ } catch (error) {
311
+ if (error.code !== 'ESRCH') console.error(`[Shutdown] ${error.message}`);
266
312
  }
267
313
  }
268
314
 
@@ -288,14 +334,19 @@ async function main() {
288
334
  hydratePath();
289
335
 
290
336
  if (opts.setup) {
291
- await ensureDependencies({ needTunnel: true, autoInstall: true });
292
- console.log('\n[OK] 环境依赖检查完成,uvx 与 cloudflared 均已就绪!');
337
+ await ensureDependencies({
338
+ needTunnel: !opts.noTunnel,
339
+ autoInstall: !opts.noAutoInstall,
340
+ allowRemoteInstall: opts.allowRemoteInstall,
341
+ });
342
+ console.log('\n[OK] 所需依赖均已就绪。');
293
343
  process.exit(0);
294
344
  }
295
345
 
296
346
  await ensureDependencies({
297
347
  needTunnel: !opts.noTunnel,
298
348
  autoInstall: !opts.noAutoInstall,
349
+ allowRemoteInstall: opts.allowRemoteInstall,
299
350
  });
300
351
 
301
352
  const token = opts.token || crypto.randomBytes(24).toString('hex');
@@ -305,10 +356,13 @@ async function main() {
305
356
  }
306
357
 
307
358
  const children = [];
359
+ const portLocks = new Map();
360
+ const childEnv = { ...process.env };
361
+ delete childEnv.MCP_TOKEN;
308
362
  let proxyServer = null;
309
363
  let shuttingDown = false;
310
364
 
311
- const shutdown = (exitCode = 0) => {
365
+ const shutdown = async (exitCode = 0) => {
312
366
  if (shuttingDown) return;
313
367
  shuttingDown = true;
314
368
  console.log('\n[Shutdown] 正在停止所有 Serena 实例与隧道...');
@@ -319,16 +373,16 @@ async function main() {
319
373
  // ignore
320
374
  }
321
375
  }
322
- for (const child of children) {
323
- killProcessTree(child);
324
- }
325
- setTimeout(() => process.exit(exitCode), 300);
376
+ await Promise.all(children.map(killProcessTree));
377
+ process.exit(exitCode);
326
378
  };
327
379
 
328
380
  process.on('SIGINT', () => shutdown(0));
329
381
  process.on('SIGTERM', () => shutdown(0));
330
382
 
331
- const reservedPorts = new Set();
383
+ process.on('exit', () => {
384
+ for (const port of portLocks.keys()) releasePort(port, portLocks);
385
+ });
332
386
  const isMultiProject = opts.projects.length > 1;
333
387
  const targets =
334
388
  opts.projects.length === 0
@@ -336,12 +390,8 @@ async function main() {
336
390
  : opts.projects;
337
391
 
338
392
  const routes = [];
339
- const startupPromises = [];
340
393
 
341
- console.log('==================================================');
342
- console.log('本次会话 Bearer Token:');
343
- console.log(token);
344
- console.log('==================================================');
394
+ if (!opts.token) console.log(`本次会话 Bearer Token: ${token}`);
345
395
 
346
396
  if (opts.projects.length === 0) {
347
397
  console.log('[Mode] 全局多项目模式(可在对话中随时指定/切换项目路径)');
@@ -352,19 +402,15 @@ async function main() {
352
402
  console.log(`[Mode] 多项目并行模式(共 ${opts.projects.length} 个项目同时启动)`);
353
403
  }
354
404
 
355
- for (const target of targets) {
356
- const port = await allocateFreePort(opts.basePort, reservedPorts);
405
+ async function startTarget(target) {
406
+ if (shuttingDown) return;
407
+ const port = await allocateFreePort(opts.basePort, portLocks);
408
+ if (shuttingDown) return;
357
409
  const prefix = isMultiProject ? `/p/${target.slug}` : '';
358
- routes.push({
359
- prefix,
360
- targetPort: port,
361
- name: target.name,
362
- projectPath: target.projectPath,
363
- });
364
410
 
365
411
  const serenaArgs = [
366
412
  '--from',
367
- 'git+https://github.com/oraios/serena',
413
+ `git+https://github.com/oraios/serena@${opts.serenaRef}`,
368
414
  'serena',
369
415
  'start-mcp-server',
370
416
  '--context',
@@ -389,35 +435,54 @@ async function main() {
389
435
  const child = spawn('uvx', serenaArgs, {
390
436
  stdio: ['ignore', 'pipe', 'pipe'],
391
437
  shell: false,
438
+ detached: !IS_WIN,
439
+ env: childEnv,
392
440
  });
393
441
  children.push(child);
394
442
 
395
443
  pipePrefixed(child.stdout, `[serena:${target.name}]`, process.stdout);
396
444
  pipePrefixed(child.stderr, `[serena:${target.name}]`, process.stderr);
397
445
 
398
- startupPromises.push(waitForPort(port, target.name, child));
446
+ await waitForPort(port, target.name, child);
447
+ child.on('exit', (code, signal) => {
448
+ if (shuttingDown) return;
449
+ console.error(`[Error] Serena [${target.name}] 已退出 (code=${code}, signal=${signal})`);
450
+ void shutdown(1);
451
+ });
452
+ return { prefix, targetPort: port, name: target.name, projectPath: target.projectPath };
399
453
  }
400
454
 
401
- console.log('[Wait] 等待所有 Serena 实例就绪(首次运行可能需要下载依赖)...');
455
+ let proxyPort;
402
456
  try {
403
- await Promise.all(startupPromises);
457
+ console.log('[Wait] 等待所有 Serena 实例就绪(首次运行可能需要下载依赖)...');
458
+ routes.push(...await Promise.all(targets.map(startTarget)));
459
+ if (shuttingDown) return;
460
+
461
+ for (let attempt = 0; attempt < 5; attempt++) {
462
+ proxyPort = await allocateFreePort(Math.min(opts.basePort + 1, 65535), portLocks);
463
+ if (shuttingDown) return;
464
+ try {
465
+ proxyServer = await startAuthProxy({
466
+ listenPort: proxyPort,
467
+ masterToken: token,
468
+ routes,
469
+ trustProxy: !opts.noTunnel,
470
+ });
471
+ break;
472
+ } catch (error) {
473
+ releasePort(proxyPort, portLocks);
474
+ if (error.code !== 'EADDRINUSE' || attempt === 4) throw error;
475
+ }
476
+ }
404
477
  } catch (err) {
405
478
  console.error(`[Error] ${err.message}`);
406
- shutdown(1);
479
+ await shutdown(1);
407
480
  return;
408
481
  }
409
482
 
410
- const proxyPort = await allocateFreePort(opts.basePort + 1, reservedPorts);
411
- proxyServer = await startAuthProxy({
412
- listenPort: proxyPort,
413
- masterToken: token,
414
- routes,
415
- });
416
-
417
483
  const printEndpoints = (baseUrl) => {
418
484
  console.log('\n==================================================');
419
485
  console.log('Serena MCP 已就绪,复制以下地址到客户端:');
420
- console.log(`Bearer Token: ${token}`);
421
486
  console.log('--------------------------------------------------');
422
487
  for (const r of routes) {
423
488
  const endpoint = `${baseUrl}${r.prefix}/mcp`;
@@ -440,6 +505,8 @@ async function main() {
440
505
  {
441
506
  stdio: ['ignore', 'pipe', 'pipe'],
442
507
  shell: false,
508
+ detached: !IS_WIN,
509
+ env: childEnv,
443
510
  }
444
511
  );
445
512
  children.push(cf);
@@ -459,6 +526,10 @@ async function main() {
459
526
 
460
527
  cf.stdout.on('data', watchTunnelUrl);
461
528
  cf.stderr.on('data', watchTunnelUrl);
529
+ cf.on('error', (error) => {
530
+ console.error(`[Error] cloudflared 启动失败: ${error.message}`);
531
+ void shutdown(1);
532
+ });
462
533
  cf.on('exit', (code) => {
463
534
  if (!shuttingDown) {
464
535
  console.error(`[Error] cloudflared 已退出 (code=${code})`);