dsh-mcp-ops 0.2.1 → 0.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.
@@ -0,0 +1,21 @@
1
+ import { createHash } from "node:crypto";
2
+ const OAUTH_CREDENTIAL_SCOPE = "mcp-client";
3
+ const HASH_LENGTH = 8;
4
+ const SLUG_MAX = 40;
5
+ function oauthKeySlug(serverName) {
6
+ const lowered = serverName.toLowerCase();
7
+ const folded = lowered.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, SLUG_MAX).replace(/-+$/g, "");
8
+ return /^[a-z]/.test(folded) ? folded : `s${folded}`;
9
+ }
10
+ function oauthCredentialKey(serverName, digest = sha256Hex) {
11
+ const hash = digest(serverName).slice(0, HASH_LENGTH);
12
+ return `${OAUTH_CREDENTIAL_SCOPE}/${oauthKeySlug(serverName)}-${hash}`;
13
+ }
14
+ function sha256Hex(value) {
15
+ return createHash("sha256").update(value).digest("hex");
16
+ }
17
+ export {
18
+ OAUTH_CREDENTIAL_SCOPE,
19
+ oauthCredentialKey,
20
+ oauthKeySlug
21
+ };
package/lib/probe.js CHANGED
@@ -1,55 +1,50 @@
1
- import * as McpClientModule from "@deepseek-ai/dsh-mcp-client";
2
- import { createScope } from "@deepseek-ai/dsh-scope";
1
+ import { createHash } from "node:crypto";
3
2
  import { errorText } from "./error-text.js";
4
3
  const PROBE_BUDGET_MS = 6e4;
5
- const PROBE_OAUTH_BUDGET_MS = 5 * 6e4;
6
- const McpClient = {
7
- name: McpClientModule.name,
8
- inject: McpClientModule.inject,
9
- Config: McpClientModule.Config,
10
- apply: McpClientModule.apply
11
- };
12
- async function withBudget(promise, budgetMs) {
13
- let timer;
14
- try {
15
- return await Promise.race([
16
- promise,
17
- new Promise((_resolve, reject) => {
18
- timer = setTimeout(() => reject(new Error(`probe timed out after ${budgetMs}ms`)), budgetMs);
19
- timer.unref?.();
20
- })
21
- ]);
22
- } finally {
23
- if (timer !== void 0) clearTimeout(timer);
24
- }
4
+ const MAX_PUBLIC_NAME_LENGTH = 64;
5
+ const INVALID_NAME_CHARS = /[^A-Za-z0-9_-]/g;
6
+ const HASH_LENGTH = 12;
7
+ function publicToolName(serverName, rawName) {
8
+ const joined = `mcp__${serverName}__${rawName}`;
9
+ const normalized = joined.replace(INVALID_NAME_CHARS, "_");
10
+ if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH) return normalized;
11
+ const hash = createHash("sha256").update(`${serverName}\0${rawName}`).digest("hex").slice(0, HASH_LENGTH);
12
+ return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
25
13
  }
26
14
  async function probeServer(ctx, config, options = {}) {
27
- const budgetMs = options.budgetMs ?? (options.oauth === true ? PROBE_OAUTH_BUDGET_MS : PROBE_BUDGET_MS);
15
+ const budgetMs = options.budgetMs ?? PROBE_BUDGET_MS;
28
16
  const started = Date.now();
29
- const key = {};
30
- const scope = createScope(ctx, key, {});
17
+ const host = ctx.get("mcpClientHost");
18
+ if (process.env.DSH_MCP_OPS_DEBUG !== void 0) {
19
+ process.stderr.write(`dsh-mcp-ops: probe(${config.serverName}) host=${host === void 0 ? "MISSING" : "ok"}
20
+ `);
21
+ }
22
+ if (host === void 0) {
23
+ return {
24
+ ok: false,
25
+ tools: [],
26
+ message: "mcpClientHost is unavailable in this composition (mount @deepseek-ai/dsh-mcp-manager to test connections)",
27
+ elapsedMs: Date.now() - started
28
+ };
29
+ }
31
30
  try {
32
- const child = scope.ctx.plugin(McpClient, McpClient.Config({
33
- ...config,
34
- // 连接失败即探测失败(不让 fiber 停在半活状态);一次性尝试,不进退避。
35
- failOnStartupError: true,
36
- reconnect: { enabled: false }
37
- }));
38
- await withBudget(child.await(), budgetMs);
39
- const prefix = `mcp__${config.serverName}__`;
40
- const tools = ctx.tools.schemas(key).filter((tool) => tool.name.startsWith(prefix)).map((tool) => ({ name: tool.name, ...tool.description === void 0 ? {} : { description: tool.description } }));
41
- return { ok: true, tools, elapsedMs: Date.now() - started };
31
+ const resolved = host.validate(config, ["probe", config.serverName]);
32
+ const result = await host.probe(resolved, { timeoutMs: budgetMs });
33
+ return {
34
+ ok: result.ok,
35
+ tools: result.ok ? result.toolNames.map((name) => ({ name: publicToolName(config.serverName, name) })) : [],
36
+ ...result.ok ? {} : { message: result.message },
37
+ elapsedMs: result.ok ? result.durationMs : Date.now() - started
38
+ };
42
39
  } catch (error) {
43
- return { ok: false, tools: [], message: errorText(error), elapsedMs: Date.now() - started };
44
- } finally {
45
- try {
46
- await scope.dispose();
47
- } catch {
48
- }
40
+ const message = errorText(error);
41
+ if (process.env.DSH_MCP_OPS_DEBUG !== void 0) process.stderr.write(`dsh-mcp-ops: probe(${config.serverName}) failed: ${message}
42
+ `);
43
+ return { ok: false, tools: [], message, elapsedMs: Date.now() - started };
49
44
  }
50
45
  }
51
46
  export {
52
47
  PROBE_BUDGET_MS,
53
- PROBE_OAUTH_BUDGET_MS,
54
- probeServer
48
+ probeServer,
49
+ publicToolName
55
50
  };
package/lib/refs.js CHANGED
@@ -1,17 +1,13 @@
1
- import { createHash } from "node:crypto";
2
1
  const REF_PREFIX = "DSH_MCP_";
3
2
  const SERVER_REF_PREFIX = `${REF_PREFIX}_`;
4
3
  const SERVER_REF_SEP = "__";
5
4
  const LEGACY_SERVER_REF_PREFIX = REF_PREFIX;
6
5
  const LEGACY_MCP_SERVER_REF_PREFIX = `${REF_PREFIX}mcp_`;
7
6
  const GLOBAL_REF_PREFIX = `${REF_PREFIX}ENV_`;
8
- const OAUTH_REF_PREFIX = `${REF_PREFIX}OAUTH_`;
9
- const OAUTH_CLIENT_REF_PREFIX = `${REF_PREFIX}OAUTH_CLIENT_`;
10
7
  const SECRET_PLACEHOLDER = "_$secret$_";
11
8
  const SERVER_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/;
12
9
  const REF_SAFE_SERVER_NAME_RE = /^[A-Za-z0-9_]{1,32}$/;
13
10
  const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
14
- const OAUTH_HASH_RE = /^[0-9a-f]{12}$/;
15
11
  const REF_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
16
12
  function refName(value) {
17
13
  if (!REF_NAME_RE.test(value)) {
@@ -54,14 +50,6 @@ function globalRef(envName) {
54
50
  }
55
51
  return refName(`${GLOBAL_REF_PREFIX}${envName}`);
56
52
  }
57
- function oauthHash(serverName) {
58
- return createHash("sha256").update(serverName, "utf8").digest("hex").slice(0, 12);
59
- }
60
- function oauthRef(serverName, client = false) {
61
- assertRefSafeServerName(serverName);
62
- const prefix = client ? OAUTH_CLIENT_REF_PREFIX : OAUTH_REF_PREFIX;
63
- return refName(`${prefix}${serverName}_${oauthHash(serverName)}`);
64
- }
65
53
  function resolveServerRef(ref, serverNames) {
66
54
  if (typeof ref !== "string") return void 0;
67
55
  const names = [...serverNames];
@@ -100,7 +88,6 @@ function legacySecretRef(serverName, envName, raw) {
100
88
  if (braced === null) return void 0;
101
89
  if (braced[1].startsWith(SERVER_REF_PREFIX)) return void 0;
102
90
  if (braced[1].startsWith(GLOBAL_REF_PREFIX)) return void 0;
103
- if (resolveOAuthRef(braced[1], [serverName]) !== void 0) return void 0;
104
91
  const hit = resolveServerRef(braced[1], [serverName]);
105
92
  if (hit === void 0 || hit.serverName !== serverName || hit.envName !== envName) return void 0;
106
93
  if (!REF_NAME_RE.test(braced[1])) return void 0;
@@ -114,21 +101,6 @@ function resolveGlobalRef(ref) {
114
101
  const name = ref.slice(GLOBAL_REF_PREFIX.length);
115
102
  return ENV_NAME_RE.test(name) ? { envName: name } : void 0;
116
103
  }
117
- function resolveOAuthRef(ref, serverNames) {
118
- if (typeof ref !== "string") return void 0;
119
- const client = ref.startsWith(OAUTH_CLIENT_REF_PREFIX);
120
- const prefix = client ? OAUTH_CLIENT_REF_PREFIX : OAUTH_REF_PREFIX;
121
- if (!ref.startsWith(prefix)) return void 0;
122
- const rest = ref.slice(prefix.length);
123
- const cut = rest.lastIndexOf("_");
124
- if (cut <= 0) return void 0;
125
- const hash = rest.slice(cut + 1);
126
- if (!OAUTH_HASH_RE.test(hash)) return void 0;
127
- const namePart = rest.slice(0, cut);
128
- const hits = [...serverNames].filter((name) => name === namePart);
129
- if (hits.length !== 1) return void 0;
130
- return { serverName: hits[0], client };
131
- }
132
104
  function upperCaseConflict(candidate, existing) {
133
105
  const upper = candidate.toUpperCase();
134
106
  return [...existing].find((name) => name !== candidate && name.toUpperCase() === upper);
@@ -138,9 +110,6 @@ export {
138
110
  GLOBAL_REF_PREFIX,
139
111
  LEGACY_MCP_SERVER_REF_PREFIX,
140
112
  LEGACY_SERVER_REF_PREFIX,
141
- OAUTH_CLIENT_REF_PREFIX,
142
- OAUTH_HASH_RE,
143
- OAUTH_REF_PREFIX,
144
113
  REF_NAME_RE,
145
114
  REF_PREFIX,
146
115
  REF_SAFE_SERVER_NAME_RE,
@@ -153,10 +122,7 @@ export {
153
122
  isLegacySecretRow,
154
123
  legacySecretRef,
155
124
  legacyServerRef,
156
- oauthHash,
157
- oauthRef,
158
125
  resolveGlobalRef,
159
- resolveOAuthRef,
160
126
  resolveServerRef,
161
127
  serverEnvRefPrefix,
162
128
  serverRef,
package/lib/service.js CHANGED
@@ -46,7 +46,7 @@ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use
46
46
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
47
47
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
48
48
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
49
- var _oauthStart_dec, _envSet_dec, _envInject_dec, _envList_dec, _jsonWrite_dec, _jsonRead_dec, _test_dec, _setEnabled_dec, _removeServer_dec, _refreshServer_dec, _upsert_dec, _release_dec, _adopt_dec, _toolsMode_dec, _toolsSet_dec, _toolsList_dec, _refresh_dec, _list_dec, _a, _init;
49
+ var _oauthSignOut_dec, _oauthCancel_dec, _oauthStart_dec, _envSet_dec, _envInject_dec, _envList_dec, _jsonWrite_dec, _jsonRead_dec, _test_dec, _setEnabled_dec, _removeServer_dec, _refreshServer_dec, _upsert_dec, _release_dec, _adopt_dec, _toolsMode_dec, _toolsSet_dec, _toolsList_dec, _refresh_dec, _list_dec, _a, _init;
50
50
  import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
51
51
  import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs";
52
52
  import { dirname, join } from "node:path";
@@ -55,20 +55,8 @@ import { createScope } from "@deepseek-ai/dsh-scope";
55
55
  import { normalizeEntry, serverEntries } from "./files/mcp-json.js";
56
56
  import { defaultWriteTarget } from "./files/locations.js";
57
57
  import { effectiveRow } from "./models.js";
58
- import { oauthRef, serverEnvRefPrefix, serverRef } from "./refs.js";
58
+ import { serverEnvRefPrefix, serverRef } from "./refs.js";
59
59
  import { credentialsDocumentPath, groupServerEnvNames, readCredentialRefNames, serverEnvNamesOf } from "./credentials-doc.js";
60
- import {
61
- awaitLoopbackCallback,
62
- buildAuthorizationUrl,
63
- createPkcePair,
64
- createState,
65
- discoverMetadata,
66
- exchangeCode,
67
- parseClient,
68
- serializeClient,
69
- serializeToken
70
- } from "./oauth.js";
71
- import { WEB_CALLBACK_PATH, awaitWebCallback, handleWebCallback, sanitizeOrigin, webCallbackUri } from "./oauth-web.js";
72
60
  import { checkServerName } from "./models.js";
73
61
  import {
74
62
  FileChangedError,
@@ -89,7 +77,7 @@ import { createDocumentText, removeEntry, setEntryEnabled, setTopLevelKey, upser
89
77
  import { errorText } from "./error-text.js";
90
78
  import { MountManager } from "./mount.js";
91
79
  import { globalRef } from "./refs.js";
92
- import { canHoldCredentialRef, legacySecretRef, legacyServerRef, resolveOAuthRef, resolveServerRef } from "./refs.js";
80
+ import { canHoldCredentialRef, legacySecretRef, legacyServerRef, resolveServerRef } from "./refs.js";
93
81
  import { cordisSourceResults, scanCordisComposition, specFromCordisConfig } from "./sources/cordis-source.js";
94
82
  import { buildSnapshot, readFileSources } from "./sources/registry.js";
95
83
  import {
@@ -124,7 +112,7 @@ function sameConnectionSpec(a, b) {
124
112
  });
125
113
  return canonicalJson(pick(a)) === canonicalJson(pick(b));
126
114
  }
127
- class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _refresh_dec = [Remote], _toolsList_dec = [Remote], _toolsSet_dec = [Remote], _toolsMode_dec = [Remote], _adopt_dec = [Remote], _release_dec = [Remote], _upsert_dec = [Remote], _refreshServer_dec = [Remote], _removeServer_dec = [Remote], _setEnabled_dec = [Remote], _test_dec = [Remote], _jsonRead_dec = [Remote], _jsonWrite_dec = [Remote], _envList_dec = [Remote], _envInject_dec = [Remote], _envSet_dec = [Remote], _oauthStart_dec = [Remote], _a) {
115
+ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _refresh_dec = [Remote], _toolsList_dec = [Remote], _toolsSet_dec = [Remote], _toolsMode_dec = [Remote], _adopt_dec = [Remote], _release_dec = [Remote], _upsert_dec = [Remote], _refreshServer_dec = [Remote], _removeServer_dec = [Remote], _setEnabled_dec = [Remote], _test_dec = [Remote], _jsonRead_dec = [Remote], _jsonWrite_dec = [Remote], _envList_dec = [Remote], _envInject_dec = [Remote], _envSet_dec = [Remote], _oauthStart_dec = [Remote], _oauthCancel_dec = [Remote], _oauthSignOut_dec = [Remote], _a) {
128
116
  /**
129
117
  * @param ctx - Host 上下文。
130
118
  * @param config - 插件配置(bundle 行 `config`)。
@@ -195,13 +183,6 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
195
183
  __publicField(this, "syncChain", Promise.resolve());
196
184
  /** 凭据更新事件的去抖定时器(B37)。 */
197
185
  __publicField(this, "credentialTimer");
198
- /**
199
- * Web 回调路由是否已经注册(B81)。
200
- *
201
- * `false` 的两种情形:组合里根本没有 `webServer`(Electron/TUI),或官方路由注册失败
202
- * (例如别的插件先占了同一路径)—— 两种都让 {@link startOAuth} 走回环,语义不变。
203
- */
204
- __publicField(this, "webCallbackReady", false);
205
186
  this.hostCtx = ctx;
206
187
  this.config = config;
207
188
  this.mounts = new MountManager(ctx);
@@ -226,25 +207,15 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
226
207
  ctx.effect(() => () => {
227
208
  if (this.credentialTimer !== void 0) clearTimeout(this.credentialTimer);
228
209
  }, "dsh-mcp-ops:credentials-timer");
229
- const webHost = ctx.get("webServer");
230
- if (webHost !== void 0) {
231
- try {
232
- ctx.effect(
233
- () => webHost.register({ kind: "exact", path: WEB_CALLBACK_PATH, handler: handleWebCallback }),
234
- "dsh-mcp-ops:oauth callback"
235
- );
236
- this.webCallbackReady = true;
237
- } catch (error) {
238
- process.stderr.write(`dsh-mcp-ops: OAuth Web \u56DE\u8C03\u8DEF\u7531\u6CE8\u518C\u5931\u8D25\uFF0C\u56DE\u9000\u56DE\u73AF\uFF1A${error instanceof Error ? error.message : String(error)}
239
- `);
240
- }
241
- }
242
210
  }
243
211
  /**
244
212
  * 凭据更新事件的落点(B37):只有"本插件认识"的引用才触发同步。
245
213
  *
246
- * 认识的三种:服务器级引用(在已知名字集合里唯一命中)、OAuth token / client 引用、
247
- * 进程级引用。其余(别的插件、用户手写的)一律忽略 —— 这就是"精确归属"。
214
+ * 认识的两种:服务器级引用(在已知名字集合里唯一命中)与进程级引用。其余(别的插件、
215
+ * 用户手写的)一律忽略 —— 这就是"精确归属"。
216
+ *
217
+ * **OAuth 凭据不在其中**(0.3.0):token 由官方 client 持有并自行监听轮换、重建连接,
218
+ * 本插件既不认识那些键,也不需要在轮换时做任何事。
248
219
  *
249
220
  * 不直接 `restart`:走一次去抖的差分 `sync()`,指纹没变就什么都不发生(自己做过的写
250
221
  * 不会引起多余重启,真轮换才会)。
@@ -253,7 +224,7 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
253
224
  */
254
225
  onCredentialUpdated(ref) {
255
226
  const names = this.snapshot.servers.map((server) => server.serverName);
256
- const owned = resolveServerRef(ref, names) !== void 0 || resolveOAuthRef(ref, names) !== void 0 || typeof ref === "string" && ref.startsWith("DSH_MCP_ENV_");
227
+ const owned = resolveServerRef(ref, names) !== void 0 || typeof ref === "string" && ref.startsWith("DSH_MCP_ENV_");
257
228
  if (!owned) return;
258
229
  if (this.credentialTimer !== void 0) clearTimeout(this.credentialTimer);
259
230
  this.credentialTimer = setTimeout(() => {
@@ -298,6 +269,37 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
298
269
  this.composition = scan;
299
270
  return scan;
300
271
  }
272
+ /**
273
+ * 官方 manager 当前**配置了**、但不属于本插件注册的服务器名。
274
+ *
275
+ * `list()` 的 `configured` 对"configured 项"和"插件注册项"都为 true(entries 是两者合并),
276
+ * 所以用 {@link MountManager.liveServerNames} 排除本插件自己的注册。
277
+ *
278
+ * @returns 名字数组(空数组表示没有外部配置)。
279
+ */
280
+ /** 官方 MCP 管理器(挂载、探测与 OAuth 授权都经它)。 */
281
+ get manager() {
282
+ return this.hostCtx.mcpManager;
283
+ }
284
+ managerOccupiedNames() {
285
+ try {
286
+ const mine = this.mounts.liveServerNames();
287
+ return this.hostCtx.mcpManager.list().filter((view) => view.configured && !mine.has(view.name)).map((view) => view.name);
288
+ } catch {
289
+ return [];
290
+ }
291
+ }
292
+ /**
293
+ * 把官方 manager 的配置名并进 cordis 源的占用名单(与补丁声明同一口径:只读 + 不重复挂)。
294
+ *
295
+ * @param inputs - 各源读取结果。
296
+ * @param names - 需要标占用的名字。
297
+ * @returns 新的源读取结果(不修改入参)。
298
+ */
299
+ withManagerOccupied(inputs, names) {
300
+ if (names.length === 0) return [...inputs];
301
+ return inputs.map((input) => input.location.kind !== "cordis" ? input : { ...input, occupied: [.../* @__PURE__ */ new Set([...input.occupied ?? [], ...names])] });
302
+ }
301
303
  /**
302
304
  * 读一份文档;文件不存在时按"空 canonical 文档"造一份。
303
305
  * @param path - 文件路径。
@@ -729,17 +731,13 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
729
731
  const globalEnv = await this.readGlobalEnv();
730
732
  const global = this.readGlobal();
731
733
  const scan = this.scanComposition();
732
- let inputs = [...readFileSources(locations), ...cordisSourceResults(scan, locations)];
734
+ const managerOccupied = this.managerOccupiedNames();
735
+ let inputs = this.withManagerOccupied([...readFileSources(locations), ...cordisSourceResults(scan, locations)], managerOccupied);
733
736
  let preliminary = buildSnapshot(inputs, overlays, []);
734
737
  if (await this.migrateLegacySecretRows(preliminary.rows)) {
735
- inputs = [...readFileSources(locations), ...cordisSourceResults(scan, locations)];
738
+ inputs = this.withManagerOccupied([...readFileSources(locations), ...cordisSourceResults(scan, locations)], managerOccupied);
736
739
  preliminary = buildSnapshot(inputs, overlays, []);
737
740
  }
738
- this.toolControl.load(
739
- this.readToolSwitches(),
740
- global.injectionMode,
741
- preliminary.rows.map((row) => row.serverName)
742
- );
743
741
  const grouped = groupServerEnvNames(this.credentialRefNames(), preliminary.rows.map((row) => row.serverName));
744
742
  const infos = await Promise.all(preliminary.rows.map(
745
743
  async (row) => await this.secretInfoOf(row, grouped.get(row.serverName) ?? [])
@@ -748,6 +746,14 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
748
746
  (row, index) => this.mountRequestOf(row, globalEnv, global.injectGlobalEnvToStdio, infos[index])
749
747
  );
750
748
  const states = await this.mounts.sync(requests);
749
+ this.toolControl.load(
750
+ this.readToolSwitches(),
751
+ global.injectionMode,
752
+ // 已知集合要带上 manager 的 configured 名:否则 `foo` 与官方 `foo_extra` 并存时,
753
+ // 最长前缀匹配会退化成首个 `__` 切分,把官方工具误判成自有。
754
+ [.../* @__PURE__ */ new Set([...preliminary.rows.map((row) => row.serverName), ...managerOccupied])],
755
+ [...this.mounts.liveServerNames()]
756
+ );
751
757
  const secretRows = new Map(preliminary.rows.map((row, index) => [row.serverName, infos[index].rows]));
752
758
  const snapshot = buildSnapshot(inputs, overlays, states, secretRows);
753
759
  this.snapshot = {
@@ -798,6 +804,7 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
798
804
  await this.ready;
799
805
  const outcome = await this.toolControl.setMode(request?.mode);
800
806
  if (!outcome.ok) return outcome;
807
+ this.snapshot = await this.sync();
801
808
  return { ok: true, value: this.toolControl.list() };
802
809
  }
803
810
  async adopt(request) {
@@ -809,6 +816,9 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
809
816
  if (declaration === void 0) {
810
817
  return failure("MCP_ADOPT_NOT_DECLARED", `\u7EC4\u5408\u5C42\u6CA1\u6709\u58F0\u660E\u540D\u4E3A ${JSON.stringify(serverName)} \u7684 MCP \u670D\u52A1\u5668`);
811
818
  }
819
+ if (declaration.adoptable === false) {
820
+ return failure("MCP_ADOPT_NOT_DECLARED", `\u670D\u52A1\u5668 ${JSON.stringify(serverName)} \u7531\u5B98\u65B9 mcp-manager \u884C\u63D0\u4F9B\uFF0C\u4E0D\u80FD\u5355\u53F0\u63A5\u7BA1\uFF1B\u8BF7\u5728\u8BE5\u884C\u7684 config.servers \u91CC\u4FEE\u6539`);
821
+ }
812
822
  if (declaration.rowId === void 0) {
813
823
  return failure("MCP_ADOPT_NO_ID", `\u58F0\u660E\u884C ${JSON.stringify(serverName)} \u6CA1\u6709 id\uFF0C\u65E0\u6CD5\u5728\u8865\u4E01\u91CC\u5B9A\u4F4D\uFF1B\u8BF7\u5148\u7ED9\u5B83\u8865\u4E00\u4E2A id`);
814
824
  }
@@ -1054,17 +1064,6 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1054
1064
  }
1055
1065
  return { ...configs, tool_switches: switches };
1056
1066
  });
1057
- for (const client of [false, true]) {
1058
- try {
1059
- const fromRef = oauthRef(from, client);
1060
- const toRef = oauthRef(to, client);
1061
- if (String(fromRef) === String(toRef)) continue;
1062
- const resolved = await this.hostCtx.credentials.resolve(fromRef);
1063
- if (resolved !== void 0 && resolved.value !== "") await this.hostCtx.credentials.set(toRef, resolved.value);
1064
- await this.hostCtx.credentials.unset(fromRef);
1065
- } catch {
1066
- }
1067
- }
1068
1067
  if (serverEnvRefPrefix(from) !== serverEnvRefPrefix(to)) {
1069
1068
  for (const envName of serverEnvNamesOf(this.credentialRefNames(), from)) {
1070
1069
  try {
@@ -1078,154 +1077,6 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1078
1077
  }
1079
1078
  }
1080
1079
  }
1081
- /**
1082
- * 取(或注册)OAuth 客户端信息。
1083
- *
1084
- * **复用条件(B82)**:缓存里的 `redirectUris` 必须**包含本次的 `redirectUri`**。
1085
- * RFC 6749 §3.1.2.3 要求授权请求的 `redirect_uri` 与注册时一致,而注册记录是持久化的 ——
1086
- * B81 之后回调可能是宿主 origin(Web 路)或稳定端口回环,换了形态/端口/origin 就会不一致,
1087
- * 只比对 clientId 会让授权服务器以含糊错误拒绝。老记录没有该字段 → 不敢复用 → 重新注册。
1088
- *
1089
- * 没存过、或需要重新注册时:有注册端点就做一次动态客户端注册(MCP 生态的通行做法)并用新的
1090
- * `redirectUris: [redirectUri]` **覆盖**缓存;注册不可用或失败时**保留**用户已有的 client
1091
- * 并留一行诊断(丢掉它等于让用户白授权一次),完全没缓存才退化到固定 client id。
1092
- *
1093
- * @param serverName - 服务器名。
1094
- * @param metadata - 服务器元数据。
1095
- * @param redirectUri - 本次授权将使用的回调地址(回环或 Web)。
1096
- * @returns 客户端信息。
1097
- */
1098
- async oauthClient(serverName, metadata, redirectUri) {
1099
- let cached;
1100
- try {
1101
- const stored = await this.hostCtx.credentials.resolve(oauthRef(serverName, true));
1102
- cached = parseClient(stored?.value);
1103
- } catch {
1104
- }
1105
- if (cached !== void 0 && cached.redirectUris?.includes(redirectUri) === true) return cached;
1106
- if (metadata.registrationEndpoint === void 0) {
1107
- if (cached === void 0) return { clientId: "dsh-mcp-ops" };
1108
- this.warnClientMismatch(serverName, redirectUri, cached, "\u670D\u52A1\u5668\u672A\u58F0\u660E\u52A8\u6001\u6CE8\u518C\u7AEF\u70B9");
1109
- return cached;
1110
- }
1111
- try {
1112
- const response = await fetch(metadata.registrationEndpoint, {
1113
- method: "POST",
1114
- headers: { "content-type": "application/json", accept: "application/json" },
1115
- body: JSON.stringify({
1116
- client_name: "dsh-mcp-ops",
1117
- redirect_uris: [redirectUri],
1118
- grant_types: ["authorization_code"],
1119
- response_types: ["code"],
1120
- token_endpoint_auth_method: "none"
1121
- })
1122
- });
1123
- if (response.ok) {
1124
- const body = await response.json();
1125
- if (typeof body.client_id === "string") {
1126
- const client = {
1127
- clientId: body.client_id,
1128
- ...typeof body.client_secret === "string" ? { clientSecret: body.client_secret } : {},
1129
- redirectUris: [redirectUri]
1130
- };
1131
- await this.hostCtx.credentials.set(oauthRef(serverName, true), serializeClient(client));
1132
- return client;
1133
- }
1134
- }
1135
- } catch {
1136
- }
1137
- if (cached !== void 0) {
1138
- this.warnClientMismatch(serverName, redirectUri, cached, "\u91CD\u65B0\u6CE8\u518C\u5931\u8D25");
1139
- return cached;
1140
- }
1141
- return { clientId: "dsh-mcp-ops" };
1142
- }
1143
- /**
1144
- * 记录"缓存的 client 与本次回调地址不匹配、且无法重新注册"(B82)。
1145
- *
1146
- * 刻意 **不静默**:这种状态下 authorize 请求很可能被授权服务器拒绝,而且错误信息通常含糊
1147
- * ("invalid_client" / "invalid redirect_uri"),把这行诊断留在 stderr 能直接对上根因。
1148
- *
1149
- * @param serverName - 服务器名。
1150
- * @param redirectUri - 本次使用的回调地址。
1151
- * @param cached - 正在沿用的缓存 client。
1152
- * @param reason - 无法重新注册的原因(人类可读)。
1153
- */
1154
- warnClientMismatch(serverName, redirectUri, cached, reason) {
1155
- const registered = cached.redirectUris === void 0 ? "\uFF08\u8001\u8BB0\u5F55\uFF0C\u672A\u8BB0\u5F55 redirect_uris\uFF09" : cached.redirectUris.length === 0 ? "\uFF08\u7A7A\uFF09" : cached.redirectUris.join(", ");
1156
- process.stderr.write(
1157
- `dsh-mcp-ops: OAuth \u6CBF\u7528\u5DF2\u6709\u5BA2\u6237\u7AEF\uFF08${serverName}\uFF09\uFF1A${reason}\uFF0C\u672C\u6B21\u56DE\u8C03\u5730\u5740 ${redirectUri}\uFF0C\u6CE8\u518C\u8BB0\u5F55\u91CC\u7684 ${registered}\uFF08client ${cached.clientId}\uFF09\u2014\u2014 \u6388\u6743\u670D\u52A1\u5668\u53EF\u80FD\u56E0 redirect_uri \u4E0D\u4E00\u81F4\u800C\u62D2\u7EDD
1158
- `
1159
- );
1160
- }
1161
- /**
1162
- * 启动一次 OAuth 授权:定回调地址 → 返回授权地址 → 后台等回调换 token 并落库(B81)。
1163
- *
1164
- * **两条回调路**:
1165
- * - `origin` 有值且 Web 路由已注册 → 固定路径的宿主 origin 回调(`awaitWebCallback` + 常驻路由);
1166
- * - 否则 → 原有的稳定端口回环(`awaitLoopbackCallback`,T3 语义不变)。
1167
- *
1168
- * 两条路只在"怎么拿到 code"上不同:`state` 校验、超时、后台换 token、落 credentials 全部共用
1169
- * 下面这一段(刻意不复制两份)。
1170
- *
1171
- * @param serverName - 服务器名。
1172
- * @param url - 服务器地址(发现元数据用)。
1173
- * @param origin - 已经过 `sanitizeOrigin` 的浏览器 origin;`undefined` = 走回环。
1174
- * @returns 授权地址与回调地址。
1175
- */
1176
- async startOAuth(serverName, url, origin) {
1177
- const metadata = await discoverMetadata(url);
1178
- const state = createState();
1179
- const useWeb = origin !== void 0 && this.webCallbackReady;
1180
- let callback;
1181
- let redirectUri;
1182
- if (useWeb) {
1183
- callback = awaitWebCallback({ origin, state, budgetMs: 5 * 6e4 }).promise;
1184
- redirectUri = webCallbackUri(origin);
1185
- } else {
1186
- let resolveReady = () => {
1187
- };
1188
- const ready = new Promise((resolve) => {
1189
- resolveReady = resolve;
1190
- });
1191
- callback = awaitLoopbackCallback({
1192
- serverName,
1193
- state,
1194
- budgetMs: 5 * 6e4,
1195
- onReady: (uri) => resolveReady(uri)
1196
- });
1197
- redirectUri = await ready;
1198
- }
1199
- const client = await this.oauthClient(serverName, metadata, redirectUri);
1200
- const pkce = createPkcePair();
1201
- const authorizeUrl = buildAuthorizationUrl({
1202
- authorizationEndpoint: metadata.authorizationEndpoint,
1203
- clientId: client.clientId,
1204
- redirectUri,
1205
- state,
1206
- challenge: pkce.challenge,
1207
- ...metadata.scopesSupported === void 0 || metadata.scopesSupported.length === 0 ? {} : { scope: metadata.scopesSupported.join(" ") }
1208
- });
1209
- void callback.then(async (result) => {
1210
- const token = await exchangeCode({
1211
- tokenEndpoint: metadata.tokenEndpoint,
1212
- code: result.code,
1213
- verifier: pkce.verifier,
1214
- clientId: client.clientId,
1215
- redirectUri: result.redirectUri,
1216
- ...client.clientSecret === void 0 ? {} : { clientSecret: client.clientSecret }
1217
- });
1218
- await this.hostCtx.credentials.set(oauthRef(serverName), serializeToken(token));
1219
- process.stderr.write(`dsh-mcp-ops: OAuth \u6388\u6743\u5B8C\u6210\uFF08${serverName}\uFF09\uFF0Ctoken \u5DF2\u5B58\u50A8
1220
- `);
1221
- }).catch((error) => {
1222
- process.stderr.write(`dsh-mcp-ops: OAuth \u6388\u6743\u5931\u8D25\uFF08${serverName}\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}
1223
- `);
1224
- });
1225
- process.stderr.write(`dsh-mcp-ops: OAuth \u6388\u6743\u5730\u5740\uFF08${serverName}\uFF09\uFF1A${authorizeUrl}
1226
- `);
1227
- return { authorizeUrl, redirectUri };
1228
- }
1229
1080
  /**
1230
1081
  * 把表单输入转成条目模型(同时算出要写进 credentials 的 secret)。
1231
1082
  *
@@ -1358,7 +1209,10 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1358
1209
  // 结果把**文件路径**当成了目录发给子进程(桌面版实测)。
1359
1210
  builtins: { MCP_JSON_DIR: sourceDirectory(row.sourcePath) },
1360
1211
  secrets: info.secrets,
1361
- secretProblems: info.problems
1212
+ secretProblems: info.problems,
1213
+ // 注入模式是**全局**状态(`configs.injectionMode`),每次同步都按当前值重算:
1214
+ // 切模式 → 注册项里的 `toolLoading` 变 → 指纹变 → 差分重建,不需要额外的重启路径。
1215
+ toolLoading: this.configs.injectionMode
1362
1216
  };
1363
1217
  }
1364
1218
  /**
@@ -1493,6 +1347,11 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1493
1347
  }
1494
1348
  const overlayPatch = {
1495
1349
  ...input.oauth === void 0 ? {} : { oauth: input.oauth },
1350
+ // scope / clientId 只在勾了 OAuth 时才有意义;取消勾选时一并清掉(否则下次勾回来会
1351
+ // 悄悄复用上次的 scope,用户以为改了其实没改)。
1352
+ ...input.oauth === true && input.oauthScope !== void 0 ? { oauthScope: input.oauthScope } : {},
1353
+ ...input.oauth === true && input.oauthClientId !== void 0 ? { oauthClientId: input.oauthClientId } : {},
1354
+ ...input.oauth === false ? { oauthScope: void 0, oauthClientId: void 0 } : {},
1496
1355
  ...input.timeoutMs !== void 0 ? { toolCallTimeoutMs: input.timeoutMs } : mode === "update" ? { toolCallTimeoutMs: void 0 } : {}
1497
1356
  };
1498
1357
  if (Object.keys(overlayPatch).length > 0) {
@@ -1650,9 +1509,10 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1650
1509
  globalEnv,
1651
1510
  injectGlobalEnv: global.injectGlobalEnvToStdio,
1652
1511
  secrets: merged,
1653
- ...input.oauth === void 0 ? {} : { overlay: { oauth: input.oauth } },
1654
- builtins: { MCP_JSON_DIR: sourceDirectory(this.targetLocation(locations)?.path ?? join(process.cwd(), ".mcp.json")) }
1655
- }, { oauth: input.oauth === true });
1512
+ ...input.oauth === void 0 ? {} : { overlay: { oauth: input.oauth, ...input.oauthScope === void 0 ? {} : { oauthScope: input.oauthScope }, ...input.oauthClientId === void 0 ? {} : { oauthClientId: input.oauthClientId } } },
1513
+ builtins: { MCP_JSON_DIR: sourceDirectory(this.targetLocation(locations)?.path ?? join(process.cwd(), ".mcp.json")) },
1514
+ toolLoading: this.configs.injectionMode
1515
+ });
1656
1516
  return {
1657
1517
  ok: true,
1658
1518
  value: {
@@ -1826,14 +1686,41 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1826
1686
  await this.ready;
1827
1687
  const serverName = typeof request?.serverName === "string" ? request.serverName : "";
1828
1688
  if (serverName === "") return failure("MCP_INVALID_SPEC", "serverName is required");
1829
- const url = typeof request?.url === "string" ? request.url : "";
1830
- if (url === "") return failure("MCP_INVALID_SPEC", "url is required for OAuth");
1831
- const origin = sanitizeOrigin(request?.origin);
1832
1689
  try {
1833
- const started = await this.startOAuth(serverName, url, origin);
1834
- return { ok: true, value: started };
1690
+ const attempt = await this.manager().startAuthorization(serverName);
1691
+ this.snapshot = await this.sync();
1692
+ return {
1693
+ ok: true,
1694
+ value: { attempt: projectAttempt(attempt), servers: this.snapshot.servers }
1695
+ };
1835
1696
  } catch (error) {
1836
- return failure("MCP_FILE_WRITE_FAILED", error instanceof Error ? error.message : String(error));
1697
+ return failure("MCP_OAUTH_FAILED", error instanceof Error ? error.message : String(error));
1698
+ }
1699
+ }
1700
+ async oauthCancel(request) {
1701
+ await this.ready;
1702
+ const serverName = typeof request?.serverName === "string" ? request.serverName : "";
1703
+ const attemptId = typeof request?.attemptId === "string" ? request.attemptId : "";
1704
+ if (serverName === "") return failure("MCP_INVALID_SPEC", "serverName is required");
1705
+ if (attemptId === "") return failure("MCP_INVALID_SPEC", "attemptId is required");
1706
+ try {
1707
+ await this.manager().cancelAuthorization(serverName, attemptId);
1708
+ this.snapshot = await this.sync();
1709
+ return { ok: true, value: { servers: this.snapshot.servers } };
1710
+ } catch (error) {
1711
+ return failure("MCP_OAUTH_FAILED", error instanceof Error ? error.message : String(error));
1712
+ }
1713
+ }
1714
+ async oauthSignOut(request) {
1715
+ await this.ready;
1716
+ const serverName = typeof request?.serverName === "string" ? request.serverName : "";
1717
+ if (serverName === "") return failure("MCP_INVALID_SPEC", "serverName is required");
1718
+ try {
1719
+ await this.manager().signOut(serverName);
1720
+ this.snapshot = await this.sync();
1721
+ return { ok: true, value: { servers: this.snapshot.servers } };
1722
+ } catch (error) {
1723
+ return failure("MCP_OAUTH_FAILED", error instanceof Error ? error.message : String(error));
1837
1724
  }
1838
1725
  }
1839
1726
  /**
@@ -1872,9 +1759,19 @@ __decorateElement(_init, 1, "envList", _envList_dec, McpOpsService);
1872
1759
  __decorateElement(_init, 1, "envInject", _envInject_dec, McpOpsService);
1873
1760
  __decorateElement(_init, 1, "envSet", _envSet_dec, McpOpsService);
1874
1761
  __decorateElement(_init, 1, "oauthStart", _oauthStart_dec, McpOpsService);
1762
+ __decorateElement(_init, 1, "oauthCancel", _oauthCancel_dec, McpOpsService);
1763
+ __decorateElement(_init, 1, "oauthSignOut", _oauthSignOut_dec, McpOpsService);
1875
1764
  __decoratorMetadata(_init, McpOpsService);
1876
1765
  /** 需要的 Host 服务:缺任何一个即不激活。 */
1877
- __publicField(McpOpsService, "inject", ["credentials", "tools"]);
1766
+ __publicField(McpOpsService, "inject", ["credentials", "tools", "mcpManager"]);
1767
+ function projectAttempt(view) {
1768
+ return {
1769
+ attemptId: String(view.id),
1770
+ phase: view.phase,
1771
+ ...view.authorizationUrl === void 0 ? {} : { authorizationUrl: view.authorizationUrl },
1772
+ ...view.lastError === void 0 ? {} : { lastError: view.lastError }
1773
+ };
1774
+ }
1878
1775
  function failure(code, message) {
1879
1776
  return { ok: false, error: { code, message } };
1880
1777
  }