dsh-mcp-ops 0.1.1 → 0.1.3

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
@@ -28,7 +28,7 @@ DeepSeek Harness(dsh)插件:在设置页管理 MCP 服务。
28
28
  dsh plugin --profile web add dsh-mcp-ops
29
29
 
30
30
  # 或本地 tarball(pnpm pack 的产物)
31
- dsh plugin --profile web add /path/to/dsh-mcp-ops-0.1.1.tgz
31
+ dsh plugin --profile web add /path/to/dsh-mcp-ops-0.1.3.tgz
32
32
 
33
33
  # 卸载
34
34
  dsh plugin --profile web remove dsh-mcp-ops
@@ -70,7 +70,7 @@ docs/ 详细设计与官方依赖落点
70
70
 
71
71
  ```sh
72
72
  pnpm run --config.verify-deps-before-run=false build && pnpm pack --pack-destination docker &&
73
- docker build --progress=plain -t founder/dsh-mcp-ops:0.1.1 -f docker/Dockerfile docker/ &&
73
+ docker build --progress=plain -t founder/dsh-mcp-ops:0.1.3 -f docker/Dockerfile docker/ &&
74
74
  HOME=/home/ubuntu docker compose -f docker/docker-compose.yaml --project-directory docker up -d --force-recreate
75
75
 
76
76
  node docker/verify.mjs # 容器端到端(装配终态 / 启动日志 / 服务侧 sync / locale 元数据 / 客户端产物)
@@ -99,8 +99,8 @@ npm publish --dry-run --registry=https://registry.npmjs.org/
99
99
  npm publish --registry=https://registry.npmjs.org/ --access public
100
100
 
101
101
  # 4) 发布后核对并打 tag
102
- npm view dsh-mcp-ops@0.1.1 --registry=https://registry.npmjs.org/
103
- git tag -a v0.1.1 -m "dsh-mcp-ops 0.1.1" && git push origin v0.1.1
102
+ npm view dsh-mcp-ops@0.1.3 --registry=https://registry.npmjs.org/
103
+ git tag -a v0.1.3 -m "dsh-mcp-ops 0.1.3" && git push origin v0.1.3
104
104
  ```
105
105
 
106
106
  72 小时内可 `npm unpublish dsh-mcp-ops@<版本>` 撤回;超时只能 `npm deprecate`。
package/lib/env.js CHANGED
@@ -1,4 +1,4 @@
1
- const BUILTIN_NAMES = ["MCP_JSON_DIR", "DSH_PROJECT_DIR", "MCP_SERVER_NAME"];
1
+ const BUILTIN_NAMES = ["MCP_JSON_DIR", "MCP_SERVER_NAME"];
2
2
  const PLACEHOLDER = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
3
3
  function resolveTemplate(template, lookup) {
4
4
  const unresolved = [];
@@ -0,0 +1,54 @@
1
+ const ERROR_SEGMENT_MAX = 240;
2
+ const ERROR_DEPTH_MAX = 4;
3
+ const ERROR_TEXT_MAX = 600;
4
+ function truncate(text, max) {
5
+ return text.length <= max ? text : `${text.slice(0, max - 1)}\u2026`;
6
+ }
7
+ function segmentOf(value) {
8
+ let message;
9
+ let code = "";
10
+ if (value instanceof Error) {
11
+ message = value.message;
12
+ if (value.name !== "" && value.name !== "Error" && !message.startsWith(value.name)) {
13
+ message = `${value.name}: ${message}`;
14
+ }
15
+ const raw = value.code;
16
+ if (typeof raw === "string" && raw !== "" && !message.includes(raw)) code = raw;
17
+ } else if (typeof value === "string") {
18
+ message = value;
19
+ } else if (value !== null && typeof value === "object") {
20
+ const record = value;
21
+ message = typeof record.message === "string" ? record.message : String(value);
22
+ if (typeof record.code === "string" && record.code !== "" && !message.includes(record.code)) code = record.code;
23
+ } else {
24
+ message = String(value);
25
+ }
26
+ const text = message.trim();
27
+ const composed = code === "" ? text : text === "" ? `[${code}]` : `${text} [${code}]`;
28
+ return truncate(composed === "" ? String(value) : composed, ERROR_SEGMENT_MAX);
29
+ }
30
+ function errorText(error) {
31
+ const seen = /* @__PURE__ */ new Set();
32
+ const segments = [];
33
+ let current = error;
34
+ while (current !== null && current !== void 0) {
35
+ if (seen.has(current) || segments.length >= ERROR_DEPTH_MAX) {
36
+ segments.push("\u2026");
37
+ break;
38
+ }
39
+ seen.add(current);
40
+ segments.push(segmentOf(current));
41
+ current = current.cause;
42
+ }
43
+ let text = "";
44
+ for (let index = segments.length - 1; index >= 0; index -= 1) {
45
+ text = index === segments.length - 1 ? segments[index] : `${segments[index]} (caused by: ${text})`;
46
+ }
47
+ return truncate(text, ERROR_TEXT_MAX);
48
+ }
49
+ export {
50
+ ERROR_DEPTH_MAX,
51
+ ERROR_SEGMENT_MAX,
52
+ ERROR_TEXT_MAX,
53
+ errorText
54
+ };
@@ -1,5 +1,9 @@
1
1
  import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs";
2
- import { dirname, join } from "node:path";
2
+ import { createHash } from "node:crypto";
3
+ import { basename, dirname, join } from "node:path";
4
+ function digestOf(bytes) {
5
+ return createHash("sha256").update(bytes).digest("hex");
6
+ }
3
7
  class JsonParseError extends Error {
4
8
  /** 出错处在文本中的偏移。 */
5
9
  offset;
@@ -238,7 +242,7 @@ function readJsonDocument(path) {
238
242
  root: parsed.root,
239
243
  style: detectStyle(text, hadBOM, parsed),
240
244
  duplicateKeys: parsed.duplicateKeys,
241
- snapshot: { mtimeMs: stats.mtimeMs, size: stats.size }
245
+ snapshot: { mtimeMs: stats.mtimeMs, size: stats.size, digest: digestOf(bytes) }
242
246
  };
243
247
  }
244
248
  function objectEntry(object, key) {
@@ -278,9 +282,27 @@ function applySplices(text, splices) {
278
282
  }
279
283
  return out;
280
284
  }
285
+ const RENAME_RETRY_DELAYS_MS = [25, 50, 100, 200, 400];
286
+ const RENAME_RETRY_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
287
+ function sleepSync(ms) {
288
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
289
+ }
290
+ function renameWithRetry(from, to, rename = renameSync) {
291
+ for (let attempt = 0; ; attempt += 1) {
292
+ try {
293
+ rename(from, to);
294
+ return;
295
+ } catch (error) {
296
+ const delay = RENAME_RETRY_DELAYS_MS[attempt];
297
+ const code = error.code;
298
+ if (delay === void 0 || code === void 0 || !RENAME_RETRY_CODES.has(code)) throw error;
299
+ sleepSync(delay);
300
+ }
301
+ }
302
+ }
281
303
  function writeFileAtomic(path, text) {
282
304
  const directory = dirname(path);
283
- const temporary = join(directory, `.${path.split("/").pop() ?? "file"}.dsh-mcp-ops.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`);
305
+ const temporary = join(directory, `.${basename(path) || "file"}.dsh-mcp-ops.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`);
284
306
  try {
285
307
  mkdirSync(directory, { recursive: true });
286
308
  const backup = `${path}.dsh-mcp-ops.bak`;
@@ -297,27 +319,35 @@ function writeFileAtomic(path, text) {
297
319
  } finally {
298
320
  closeSync(handle);
299
321
  }
300
- renameSync(temporary, path);
322
+ renameWithRetry(temporary, path);
301
323
  const stats = statSync(path);
302
- return { mtimeMs: stats.mtimeMs, size: stats.size };
324
+ return { mtimeMs: stats.mtimeMs, size: stats.size, digest: digestOf(Buffer.from(text, "utf8")) };
303
325
  } catch (error) {
304
326
  try {
305
327
  if (existsSync(temporary)) unlinkSync(temporary);
306
328
  } catch {
307
329
  }
308
- throw new FileWriteError(`cannot write ${path}: ${error instanceof Error ? error.message : String(error)}`, error);
330
+ const hint = RENAME_RETRY_CODES.has(error.code ?? "") ? "\uFF08\u5DF2\u91CD\u8BD5\u4ECD\u5931\u8D25\uFF1A\u76EE\u6807\u6587\u4EF6\u53EF\u80FD\u6B63\u88AB\u7F16\u8F91\u5668 / \u6740\u6BD2\u626B\u63CF / \u540C\u6B65\u76D8\u5360\u7528\uFF0C\u5173\u95ED\u76F8\u5173\u7A0B\u5E8F\u540E\u91CD\u8BD5\uFF09" : "";
331
+ throw new FileWriteError(`cannot write ${path}: ${error instanceof Error ? error.message : String(error)}${hint}`, error);
332
+ }
333
+ }
334
+ function assertSameSnapshot(path, snapshot, stats) {
335
+ const metadata = `mtime ${snapshot.mtimeMs} \u2192 ${stats.mtimeMs}, size ${snapshot.size} \u2192 ${stats.size}`;
336
+ const digest = digestOf(readFileSync(path));
337
+ if (digest !== snapshot.digest) {
338
+ throw new FileChangedError(
339
+ `${path} changed on disk after it was read (${metadata}, sha256 ${snapshot.digest.slice(0, 12)} \u2192 ${digest.slice(0, 12)}); refresh and retry`
340
+ );
341
+ }
342
+ if (stats.mtimeMs !== snapshot.mtimeMs || stats.size !== snapshot.size) {
343
+ throw new FileChangedError(`${path} metadata changed on disk after it was read (${metadata}); refresh and retry`);
309
344
  }
310
345
  }
311
346
  function assertUnchanged(document) {
312
347
  if (!existsSync(document.path)) {
313
348
  throw new FileChangedError(`${document.path} was removed after it was read`);
314
349
  }
315
- const stats = statSync(document.path);
316
- if (stats.mtimeMs !== document.snapshot.mtimeMs || stats.size !== document.snapshot.size) {
317
- throw new FileChangedError(
318
- `${document.path} changed on disk after it was read (mtime ${document.snapshot.mtimeMs} \u2192 ${stats.mtimeMs}, size ${document.snapshot.size} \u2192 ${stats.size}); refresh and retry`
319
- );
320
- }
350
+ assertSameSnapshot(document.path, document.snapshot, statSync(document.path));
321
351
  }
322
352
  function assertStillAbsent(document) {
323
353
  assertFileUnchanged(document.path, void 0);
@@ -332,12 +362,7 @@ function assertFileUnchanged(path, snapshot) {
332
362
  if (!existsSync(path)) {
333
363
  throw new FileChangedError(`${path} was removed after it was read`);
334
364
  }
335
- const stats = statSync(path);
336
- if (stats.mtimeMs !== snapshot.mtimeMs || stats.size !== snapshot.size) {
337
- throw new FileChangedError(
338
- `${path} changed on disk after it was read (mtime ${snapshot.mtimeMs} \u2192 ${stats.mtimeMs}, size ${snapshot.size} \u2192 ${stats.size}); refresh and retry`
339
- );
340
- }
365
+ assertSameSnapshot(path, snapshot, statSync(path));
341
366
  }
342
367
  function writeFileSyncSafely(path, bytes) {
343
368
  const handle = openSync(path, "w", 420);
@@ -356,10 +381,12 @@ export {
356
381
  assertStillAbsent,
357
382
  assertUnchanged,
358
383
  detectStyle,
384
+ digestOf,
359
385
  linePrefixOf,
360
386
  objectEntry,
361
387
  parseJsonText,
362
388
  readJsonDocument,
389
+ renameWithRetry,
363
390
  stringifyValue,
364
391
  toPlain,
365
392
  writeFileAtomic
@@ -1,10 +1,24 @@
1
1
  import { homedir } from "node:os";
2
- import { isAbsolute, join, resolve } from "node:path";
2
+ import { dirname, isAbsolute, join, resolve } from "node:path";
3
3
  function expandHome(path, home) {
4
4
  if (path === "~") return home;
5
- if (path.startsWith("~/")) return join(home, path.slice(2));
5
+ if (path.startsWith("~/") || path.startsWith("~\\")) return join(home, path.slice(2));
6
6
  return isAbsolute(path) ? path : resolve(path);
7
7
  }
8
+ function sourceDirectory(path) {
9
+ return dirname(path);
10
+ }
11
+ function canonicalPathKey(path, platform = process.platform) {
12
+ let key = platform === "win32" ? path.replace(/\\/g, "/") : path;
13
+ const trimmed = key.replace(/\/+$/, "");
14
+ if (trimmed !== "" && !/^[A-Za-z]:$/.test(trimmed)) key = trimmed;
15
+ if (platform === "darwin") key = key.normalize("NFC");
16
+ if (platform === "win32" || platform === "darwin") key = key.toLowerCase();
17
+ return key;
18
+ }
19
+ function samePath(a, b, platform = process.platform) {
20
+ return canonicalPathKey(a, platform) === canonicalPathKey(b, platform);
21
+ }
8
22
  function profileFromArgv(argv = process.argv) {
9
23
  const index = argv.indexOf("--profile");
10
24
  const value = index >= 0 ? argv[index + 1] : void 0;
@@ -13,13 +27,10 @@ function profileFromArgv(argv = process.argv) {
13
27
  function resolveDshPaths(options = {}) {
14
28
  const env = options.env ?? process.env;
15
29
  const home = options.home ?? homedir();
16
- const cwd = expandHome(options.cwd ?? process.cwd(), home);
17
30
  const text = (value) => value !== void 0 && value.trim() !== "" ? value.trim() : void 0;
18
31
  const profile = options.profile ?? profileFromArgv();
19
32
  return {
20
- home,
21
33
  dshHome: expandHome(text(env.DSH_HOME) ?? join(home, ".dsh"), home),
22
- projectDir: expandHome(text(env.DSH_MCP_PROJECT_DIR) ?? cwd, home),
23
34
  ...profile === void 0 || profile === "" ? {} : { profile }
24
35
  };
25
36
  }
@@ -46,9 +57,12 @@ function defaultWriteTarget(locations) {
46
57
  return target;
47
58
  }
48
59
  export {
60
+ canonicalPathKey,
49
61
  defaultWriteTarget,
50
62
  expandHome,
51
63
  profileFromArgv,
52
64
  resolveDshPaths,
53
- resolveLocations
65
+ resolveLocations,
66
+ samePath,
67
+ sourceDirectory
54
68
  };
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync, statSync } from "node:fs";
2
- import { assertFileUnchanged, writeFileAtomic } from "./json-document.js";
2
+ import { assertFileUnchanged, digestOf, writeFileAtomic } from "./json-document.js";
3
3
  const MANAGED_OWNER = "dsh-mcp-ops";
4
4
  const MANAGED_BEGIN_SUFFIX = " managed >>>";
5
5
  const MANAGED_END_SUFFIX = " managed <<<";
@@ -95,14 +95,14 @@ function writeManagedBlock(path, rowIds, owner = MANAGED_OWNER, createdPaths = [
95
95
  const snapshot = present ? snapshotOf(path) : void 0;
96
96
  const text = present ? readFileSync(path, "utf8") : "";
97
97
  const next = upsertManagedBlock(text, rowIds, owner, createdPaths);
98
- if (next === text) return { rowIds: [...rowIds], snapshot: { mtimeMs: 0, size: text.length }, text: next };
98
+ if (next === text) return { rowIds: [...rowIds], snapshot: { mtimeMs: 0, size: text.length, digest: "" }, text: next };
99
99
  assertFileUnchanged(path, snapshot);
100
100
  const written = writeFileAtomic(path, next);
101
101
  return { rowIds: [...rowIds], snapshot: written, text: next };
102
102
  }
103
103
  function snapshotOf(path) {
104
104
  const stats = statSync(path);
105
- return { mtimeMs: stats.mtimeMs, size: stats.size };
105
+ return { mtimeMs: stats.mtimeMs, size: stats.size, digest: digestOf(readFileSync(path)) };
106
106
  }
107
107
  export {
108
108
  MANAGED_BEGIN_SUFFIX,
package/lib/mount.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as McpClientModule from "@deepseek-ai/dsh-mcp-client";
2
2
  import { buildChildEnv, makeLookup, resolveEnv, resolveHeaders } from "./env.js";
3
+ import { errorText } from "./error-text.js";
3
4
  import { isTokenFresh, parseToken } from "./oauth.js";
4
5
  import { probeServer } from "./probe.js";
5
6
  import { SERVER_NAME_RE, isLegacySecretRow, oauthRef } from "./refs.js";
@@ -9,9 +10,6 @@ const McpClient = {
9
10
  Config: McpClientModule.Config,
10
11
  apply: McpClientModule.apply
11
12
  };
12
- function errorText(error) {
13
- return error instanceof Error ? error.message : String(error);
14
- }
15
13
  class MountManager {
16
14
  /** 宿主上下文。 */
17
15
  ctx;
package/lib/probe.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as McpClientModule from "@deepseek-ai/dsh-mcp-client";
2
2
  import { createScope } from "@deepseek-ai/dsh-scope";
3
- const PROBE_BUDGET_MS = 15e3;
3
+ import { errorText } from "./error-text.js";
4
+ const PROBE_BUDGET_MS = 6e4;
4
5
  const PROBE_OAUTH_BUDGET_MS = 5 * 6e4;
5
6
  const McpClient = {
6
7
  name: McpClientModule.name,
@@ -8,10 +9,6 @@ const McpClient = {
8
9
  Config: McpClientModule.Config,
9
10
  apply: McpClientModule.apply
10
11
  };
11
- function errorText(error) {
12
- if (error instanceof Error) return error.message;
13
- return String(error);
14
- }
15
12
  async function withBudget(promise, budgetMs) {
16
13
  let timer;
17
14
  try {
package/lib/service.js CHANGED
@@ -82,9 +82,10 @@ import {
82
82
  toPlain,
83
83
  writeFileAtomic
84
84
  } from "./files/json-document.js";
85
- import { resolveDshPaths, resolveLocations } from "./files/locations.js";
85
+ import { resolveDshPaths, resolveLocations, samePath, sourceDirectory } from "./files/locations.js";
86
86
  import { readManagedBlock, writeManagedBlock } from "./files/patch-writer.js";
87
87
  import { createDocumentText, removeEntry, setEntryEnabled, setTopLevelKey, upsertEntry } from "./files/writer.js";
88
+ import { errorText } from "./error-text.js";
88
89
  import { MountManager } from "./mount.js";
89
90
  import { globalRef } from "./refs.js";
90
91
  import { canHoldCredentialRef, legacySecretRef, legacyServerRef, resolveOAuthRef, resolveServerRef } from "./refs.js";
@@ -309,7 +310,9 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
309
310
  root: parsed.root,
310
311
  style: detectStyle(text, false, parsed),
311
312
  duplicateKeys: parsed.duplicateKeys,
312
- snapshot: { mtimeMs: 0, size: 0 }
313
+ // "文件不存在"的哨兵快照:`digest: ''` 表示没有内容基准,守卫按 `mtimeMs/size` 两个 0
314
+ // 识别这一支并改走 `assertStillAbsent()`(见 `assertWritable`)。
315
+ snapshot: { mtimeMs: 0, size: 0, digest: "" }
313
316
  };
314
317
  }
315
318
  /**
@@ -838,7 +841,8 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
838
841
  const text = existsSync(patchPath) ? readFileSync(patchPath, "utf8") : "";
839
842
  const block = readManagedBlock(text);
840
843
  const rowIds = block.rowIds.includes(declaration.rowId) ? block.rowIds : [...block.rowIds, declaration.rowId];
841
- const created = entryWritten && !block.created.includes(target.path) ? [...block.created, target.path] : block.created;
844
+ const alreadyRecorded = block.created.some((entry) => samePath(entry, target.path));
845
+ const created = entryWritten && !alreadyRecorded ? [...block.created, target.path] : block.created;
842
846
  if (rowIds.length !== block.rowIds.length || created.length !== block.created.length) {
843
847
  writeManagedBlock(patchPath, rowIds, void 0, created);
844
848
  }
@@ -896,7 +900,7 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
896
900
  return failure("MCP_RELEASE_FAILED", `\u65E0\u6CD5\u5199\u5165 ${patchPath}\uFF1A${error instanceof Error ? error.message : String(error)}`);
897
901
  }
898
902
  const expected = specFromCordisConfig(declaration);
899
- const createdByUs = target !== void 0 && block.created.includes(target.path);
903
+ const createdByUs = target !== void 0 && block.created.some((entry) => samePath(entry, target.path));
900
904
  if (createdByUs && expected !== void 0 && this.hasEntry(target.path, serverName)) {
901
905
  try {
902
906
  if (this.entryEquals(target.path, serverName, expected)) {
@@ -1343,7 +1347,11 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1343
1347
  ...row.occupiedByComposition ? { occupiedByComposition: true } : {},
1344
1348
  globalEnv,
1345
1349
  injectGlobalEnv: row.overlay?.injectGlobalEnv ?? injectDefault,
1346
- builtins: { MCP_JSON_DIR: row.sourcePath.replace(/\/[^/]*$/, "") },
1350
+ // `sourceDirectory()` 就是 `dirname`,但走它有两个理由:① 它是设计文档里
1351
+ // `${MCP_JSON_DIR}` =「该条目所属文件所在目录」的落点,改错会立刻在这里看见;
1352
+ // ② 历史上这里写的是 `replace(/\/[^/]*$/, '')`,Windows 路径里没有 `/`,
1353
+ // 结果把**文件路径**当成了目录发给子进程(桌面版实测)。
1354
+ builtins: { MCP_JSON_DIR: sourceDirectory(row.sourcePath) },
1347
1355
  secrets: info.secrets,
1348
1356
  secretProblems: info.problems
1349
1357
  };
@@ -1638,7 +1646,7 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1638
1646
  injectGlobalEnv: global.injectGlobalEnvToStdio,
1639
1647
  secrets: merged,
1640
1648
  ...input.oauth === void 0 ? {} : { overlay: { oauth: input.oauth } },
1641
- builtins: { MCP_JSON_DIR: dirname(this.targetLocation(locations)?.path ?? join(process.cwd(), ".mcp.json")) }
1649
+ builtins: { MCP_JSON_DIR: sourceDirectory(this.targetLocation(locations)?.path ?? join(process.cwd(), ".mcp.json")) }
1642
1650
  }, { oauth: input.oauth === true });
1643
1651
  return {
1644
1652
  ok: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mcp-ops",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "MCP 服务管理:增删改查与启停、连接测试、工具按需检索与全量注入、进程级与服务级环境变量(含密钥);MCP service management: CRUD, connection tests, tool injection, environment variables and secrets",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",