dsh-mcp-ops 0.2.0 → 0.2.2

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,81 @@
1
+ import {
2
+ discoverMetadata,
3
+ isTokenFresh,
4
+ parseClient,
5
+ parseToken,
6
+ refreshAccessToken,
7
+ serializeToken
8
+ } from "./oauth.js";
9
+ import { oauthAccessRef, oauthRef } from "./refs.js";
10
+ async function readToken(credentials, serverName) {
11
+ try {
12
+ const resolved = await credentials.resolve(oauthRef(serverName));
13
+ return parseToken(resolved?.value);
14
+ } catch {
15
+ return void 0;
16
+ }
17
+ }
18
+ async function writeToken(credentials, serverName, token) {
19
+ const text = serializeToken(token);
20
+ const recordRef = oauthRef(serverName);
21
+ const currentRecord = await credentials.resolve(recordRef);
22
+ if (currentRecord?.value !== text) await credentials.set(recordRef, text);
23
+ const ref = oauthAccessRef(serverName);
24
+ const current = await credentials.resolve(ref);
25
+ if (current?.value !== token.accessToken) await credentials.set(ref, token.accessToken);
26
+ }
27
+ async function ensureFreshToken(credentials, serverName, url, options = {}) {
28
+ const stored = await readToken(credentials, serverName);
29
+ if (stored === void 0) return { refreshed: false, error: "no stored token" };
30
+ if (isTokenFresh(stored)) {
31
+ const ref = oauthAccessRef(serverName);
32
+ const current = await credentials.resolve(ref);
33
+ if (current?.value !== stored.accessToken) await credentials.set(ref, stored.accessToken);
34
+ return { token: stored, refreshed: false, accessRef: ref };
35
+ }
36
+ if (stored.refreshToken === void 0 || stored.refreshToken === "") {
37
+ return { refreshed: false, error: "access token expired and no refresh_token is stored" };
38
+ }
39
+ try {
40
+ const metadata = await discoverMetadata(url, options.fetchImpl);
41
+ let clientId = "dsh-mcp-ops";
42
+ let clientSecret;
43
+ try {
44
+ const cached = await credentials.resolve(oauthRef(serverName, true));
45
+ const client = parseClient(cached?.value);
46
+ if (client !== void 0) {
47
+ clientId = client.clientId;
48
+ clientSecret = client.clientSecret;
49
+ }
50
+ } catch {
51
+ }
52
+ const refreshed = await refreshAccessToken({
53
+ tokenEndpoint: metadata.tokenEndpoint,
54
+ refreshToken: stored.refreshToken,
55
+ clientId,
56
+ ...clientSecret === void 0 ? {} : { clientSecret },
57
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
58
+ });
59
+ await writeToken(credentials, serverName, refreshed);
60
+ return { token: refreshed, refreshed: true, accessRef: oauthAccessRef(serverName) };
61
+ } catch (error) {
62
+ return {
63
+ refreshed: false,
64
+ error: `token refresh failed: ${error instanceof Error ? error.message : String(error)}`
65
+ };
66
+ }
67
+ }
68
+ async function clearToken(credentials, serverName) {
69
+ for (const ref of [oauthRef(serverName), oauthAccessRef(serverName), oauthRef(serverName, true)]) {
70
+ try {
71
+ await credentials.unset(ref);
72
+ } catch {
73
+ }
74
+ }
75
+ }
76
+ export {
77
+ clearToken,
78
+ ensureFreshToken,
79
+ readToken,
80
+ writeToken
81
+ };
package/lib/oauth-web.js CHANGED
@@ -94,6 +94,7 @@ function handleWebCallback(req, res) {
94
94
  }
95
95
  const code = url.searchParams.get("code");
96
96
  const state = url.searchParams.get("state");
97
+ const iss = url.searchParams.get("iss");
97
98
  if (code === null || code === "" || state === null || state === "" || url.searchParams.getAll("code").length !== 1 || url.searchParams.getAll("state").length !== 1) {
98
99
  send(400, '<!doctype html><meta charset="utf-8"><p>\u56DE\u8C03\u53C2\u6570\u4E0D\u5408\u6CD5\uFF08code/state \u7F3A\u5931\u6216\u91CD\u590D\uFF09\u3002</p>');
99
100
  return;
@@ -104,7 +105,7 @@ function handleWebCallback(req, res) {
104
105
  send(known ? 410 : 400, known ? '<!doctype html><meta charset="utf-8"><p>\u8FD9\u6B21\u6388\u6743\u5DF2\u7ECF\u7ED3\u675F\uFF08\u91CD\u590D\u56DE\u8C03\u6216\u5DF2\u8D85\u65F6\uFF09\u3002</p>' : '<!doctype html><meta charset="utf-8"><p>\u56DE\u8C03\u53C2\u6570\u4E0D\u5408\u6CD5\uFF08state \u6821\u9A8C\u5931\u8D25\uFF09\u3002</p>');
105
106
  return;
106
107
  }
107
- candidate.settle({ code, redirectUri: candidate.redirectUri });
108
+ candidate.settle({ code, redirectUri: candidate.redirectUri, ...iss === null ? {} : { iss } });
108
109
  send(200, SUCCESS_HTML);
109
110
  }
110
111
  export {
package/lib/oauth.js CHANGED
@@ -106,6 +106,7 @@ async function discoverMetadata(issuerUrl, fetchImpl = fetch) {
106
106
  continue;
107
107
  }
108
108
  return {
109
+ ...typeof body.issuer === "string" && body.issuer !== "" ? { issuer: body.issuer } : {},
109
110
  authorizationEndpoint,
110
111
  tokenEndpoint,
111
112
  ...typeof body.registration_endpoint === "string" ? { registrationEndpoint: body.registration_endpoint } : {},
@@ -144,6 +145,31 @@ async function exchangeCode(options) {
144
145
  ...typeof payload.token_type === "string" ? { tokenType: payload.token_type } : {}
145
146
  };
146
147
  }
148
+ async function refreshAccessToken(options) {
149
+ const fetchImpl = options.fetchImpl ?? fetch;
150
+ const body = new URLSearchParams({
151
+ grant_type: "refresh_token",
152
+ refresh_token: options.refreshToken,
153
+ client_id: options.clientId
154
+ });
155
+ if (options.clientSecret !== void 0) body.set("client_secret", options.clientSecret);
156
+ const response = await fetchImpl(options.tokenEndpoint, {
157
+ method: "POST",
158
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
159
+ body: body.toString()
160
+ });
161
+ if (!response.ok) throw new Error(`token refresh failed: HTTP ${response.status}`);
162
+ const payload = await response.json();
163
+ if (typeof payload.access_token !== "string" || payload.access_token === "") {
164
+ throw new Error("token refresh failed: response has no access_token");
165
+ }
166
+ return {
167
+ accessToken: payload.access_token,
168
+ ...typeof payload.refresh_token === "string" ? { refreshToken: payload.refresh_token } : { refreshToken: options.refreshToken },
169
+ ...typeof payload.expires_in === "number" ? { expiresAt: Date.now() + payload.expires_in * 1e3 } : {},
170
+ ...typeof payload.token_type === "string" ? { tokenType: payload.token_type } : {}
171
+ };
172
+ }
147
173
  async function awaitLoopbackCallback(options) {
148
174
  const budgetMs = options.budgetMs ?? 5 * 6e4;
149
175
  let server;
@@ -184,6 +210,7 @@ async function awaitLoopbackCallback(options) {
184
210
  }
185
211
  const code = url.searchParams.get("code");
186
212
  const state = url.searchParams.get("state");
213
+ const iss = url.searchParams.get("iss");
187
214
  const error = url.searchParams.get("error");
188
215
  const finish = (status, text) => {
189
216
  response.writeHead(status, { "content-type": "text/html; charset=utf-8" });
@@ -203,7 +230,7 @@ async function awaitLoopbackCallback(options) {
203
230
  finish(200, "\u6388\u6743\u5B8C\u6210\uFF0C\u53EF\u4EE5\u5173\u95ED\u672C\u9875\u3002");
204
231
  clearTimeout(timer);
205
232
  server.close();
206
- resolve({ code, redirectUri });
233
+ resolve({ code, redirectUri, ...iss === null ? {} : { iss } });
207
234
  });
208
235
  });
209
236
  }
@@ -223,6 +250,7 @@ export {
223
250
  oauthPortFor,
224
251
  parseClient,
225
252
  parseToken,
253
+ refreshAccessToken,
226
254
  serializeClient,
227
255
  serializeToken
228
256
  };
package/lib/probe.js CHANGED
@@ -1,55 +1,36 @@
1
- import * as McpClientModule from "@deepseek-ai/dsh-mcp-client";
2
- import { createScope } from "@deepseek-ai/dsh-scope";
1
+ import { createHash } from "node:crypto";
2
+ import * as McpClient from "@deepseek-ai/dsh-mcp-client";
3
3
  import { errorText } from "./error-text.js";
4
4
  const PROBE_BUDGET_MS = 6e4;
5
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
- }
6
+ const MAX_PUBLIC_NAME_LENGTH = 64;
7
+ const INVALID_NAME_CHARS = /[^A-Za-z0-9_-]/g;
8
+ const HASH_LENGTH = 12;
9
+ function publicToolName(serverName, rawName) {
10
+ const joined = `mcp__${serverName}__${rawName}`;
11
+ const normalized = joined.replace(INVALID_NAME_CHARS, "_");
12
+ if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH) return normalized;
13
+ const hash = createHash("sha256").update(`${serverName}\0${rawName}`).digest("hex").slice(0, HASH_LENGTH);
14
+ return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
25
15
  }
26
16
  async function probeServer(ctx, config, options = {}) {
27
17
  const budgetMs = options.budgetMs ?? (options.oauth === true ? PROBE_OAUTH_BUDGET_MS : PROBE_BUDGET_MS);
28
18
  const started = Date.now();
29
- const key = {};
30
- const scope = createScope(ctx, key, {});
31
19
  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 };
20
+ const result = await McpClient.probeServer(ctx, McpClient.Config(config), { timeoutMs: budgetMs });
21
+ return {
22
+ ok: result.ok,
23
+ tools: result.ok ? result.toolNames.map((name) => ({ name: publicToolName(config.serverName, name) })) : [],
24
+ ...result.ok ? {} : { message: result.message },
25
+ elapsedMs: result.ok ? result.durationMs : Date.now() - started
26
+ };
42
27
  } catch (error) {
43
28
  return { ok: false, tools: [], message: errorText(error), elapsedMs: Date.now() - started };
44
- } finally {
45
- try {
46
- await scope.dispose();
47
- } catch {
48
- }
49
29
  }
50
30
  }
51
31
  export {
52
32
  PROBE_BUDGET_MS,
53
33
  PROBE_OAUTH_BUDGET_MS,
54
- probeServer
34
+ probeServer,
35
+ publicToolName
55
36
  };
package/lib/refs.js CHANGED
@@ -7,6 +7,7 @@ const LEGACY_MCP_SERVER_REF_PREFIX = `${REF_PREFIX}mcp_`;
7
7
  const GLOBAL_REF_PREFIX = `${REF_PREFIX}ENV_`;
8
8
  const OAUTH_REF_PREFIX = `${REF_PREFIX}OAUTH_`;
9
9
  const OAUTH_CLIENT_REF_PREFIX = `${REF_PREFIX}OAUTH_CLIENT_`;
10
+ const OAUTH_ACCESS_REF_PREFIX = `${REF_PREFIX}OAUTH_AT_`;
10
11
  const SECRET_PLACEHOLDER = "_$secret$_";
11
12
  const SERVER_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/;
12
13
  const REF_SAFE_SERVER_NAME_RE = /^[A-Za-z0-9_]{1,32}$/;
@@ -62,6 +63,10 @@ function oauthRef(serverName, client = false) {
62
63
  const prefix = client ? OAUTH_CLIENT_REF_PREFIX : OAUTH_REF_PREFIX;
63
64
  return refName(`${prefix}${serverName}_${oauthHash(serverName)}`);
64
65
  }
66
+ function oauthAccessRef(serverName) {
67
+ assertRefSafeServerName(serverName);
68
+ return refName(`${OAUTH_ACCESS_REF_PREFIX}${serverName}_${oauthHash(serverName)}`);
69
+ }
65
70
  function resolveServerRef(ref, serverNames) {
66
71
  if (typeof ref !== "string") return void 0;
67
72
  const names = [...serverNames];
@@ -117,7 +122,8 @@ function resolveGlobalRef(ref) {
117
122
  function resolveOAuthRef(ref, serverNames) {
118
123
  if (typeof ref !== "string") return void 0;
119
124
  const client = ref.startsWith(OAUTH_CLIENT_REF_PREFIX);
120
- const prefix = client ? OAUTH_CLIENT_REF_PREFIX : OAUTH_REF_PREFIX;
125
+ const access = !client && ref.startsWith(OAUTH_ACCESS_REF_PREFIX);
126
+ const prefix = client ? OAUTH_CLIENT_REF_PREFIX : access ? OAUTH_ACCESS_REF_PREFIX : OAUTH_REF_PREFIX;
121
127
  if (!ref.startsWith(prefix)) return void 0;
122
128
  const rest = ref.slice(prefix.length);
123
129
  const cut = rest.lastIndexOf("_");
@@ -127,7 +133,7 @@ function resolveOAuthRef(ref, serverNames) {
127
133
  const namePart = rest.slice(0, cut);
128
134
  const hits = [...serverNames].filter((name) => name === namePart);
129
135
  if (hits.length !== 1) return void 0;
130
- return { serverName: hits[0], client };
136
+ return { serverName: hits[0], client, ...access ? { access: true } : {} };
131
137
  }
132
138
  function upperCaseConflict(candidate, existing) {
133
139
  const upper = candidate.toUpperCase();
@@ -138,6 +144,7 @@ export {
138
144
  GLOBAL_REF_PREFIX,
139
145
  LEGACY_MCP_SERVER_REF_PREFIX,
140
146
  LEGACY_SERVER_REF_PREFIX,
147
+ OAUTH_ACCESS_REF_PREFIX,
141
148
  OAUTH_CLIENT_REF_PREFIX,
142
149
  OAUTH_HASH_RE,
143
150
  OAUTH_REF_PREFIX,
@@ -153,6 +160,7 @@ export {
153
160
  isLegacySecretRow,
154
161
  legacySecretRef,
155
162
  legacyServerRef,
163
+ oauthAccessRef,
156
164
  oauthHash,
157
165
  oauthRef,
158
166
  resolveGlobalRef,
package/lib/service.js CHANGED
@@ -55,7 +55,7 @@ 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 { oauthAccessRef, oauthRef, serverEnvRefPrefix, serverRef } from "./refs.js";
59
59
  import { credentialsDocumentPath, groupServerEnvNames, readCredentialRefNames, serverEnvNamesOf } from "./credentials-doc.js";
60
60
  import {
61
61
  awaitLoopbackCallback,
@@ -65,8 +65,7 @@ import {
65
65
  discoverMetadata,
66
66
  exchangeCode,
67
67
  parseClient,
68
- serializeClient,
69
- serializeToken
68
+ serializeClient
70
69
  } from "./oauth.js";
71
70
  import { WEB_CALLBACK_PATH, awaitWebCallback, handleWebCallback, sanitizeOrigin, webCallbackUri } from "./oauth-web.js";
72
71
  import { checkServerName } from "./models.js";
@@ -88,6 +87,8 @@ import { readManagedBlock, writeManagedBlock } from "./files/patch-writer.js";
88
87
  import { createDocumentText, removeEntry, setEntryEnabled, setTopLevelKey, upsertEntry } from "./files/writer.js";
89
88
  import { errorText } from "./error-text.js";
90
89
  import { MountManager } from "./mount.js";
90
+ import { clearToken, writeToken } from "./oauth-store.js";
91
+ import { systemFetch } from "./system-ca.js";
91
92
  import { globalRef } from "./refs.js";
92
93
  import { canHoldCredentialRef, legacySecretRef, legacyServerRef, resolveOAuthRef, resolveServerRef } from "./refs.js";
93
94
  import { cordisSourceResults, scanCordisComposition, specFromCordisConfig } from "./sources/cordis-source.js";
@@ -298,6 +299,33 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
298
299
  this.composition = scan;
299
300
  return scan;
300
301
  }
302
+ /**
303
+ * 官方 manager 当前**配置了**、但不属于本插件注册的服务器名。
304
+ *
305
+ * `list()` 的 `configured` 对"configured 项"和"插件注册项"都为 true(entries 是两者合并),
306
+ * 所以用 {@link MountManager.liveServerNames} 排除本插件自己的注册。
307
+ *
308
+ * @returns 名字数组(空数组表示没有外部配置)。
309
+ */
310
+ managerOccupiedNames() {
311
+ try {
312
+ const mine = this.mounts.liveServerNames();
313
+ return this.hostCtx.mcpManager.list().filter((view) => view.configured && !mine.has(view.name)).map((view) => view.name);
314
+ } catch {
315
+ return [];
316
+ }
317
+ }
318
+ /**
319
+ * 把官方 manager 的配置名并进 cordis 源的占用名单(与补丁声明同一口径:只读 + 不重复挂)。
320
+ *
321
+ * @param inputs - 各源读取结果。
322
+ * @param names - 需要标占用的名字。
323
+ * @returns 新的源读取结果(不修改入参)。
324
+ */
325
+ withManagerOccupied(inputs, names) {
326
+ if (names.length === 0) return [...inputs];
327
+ return inputs.map((input) => input.location.kind !== "cordis" ? input : { ...input, occupied: [.../* @__PURE__ */ new Set([...input.occupied ?? [], ...names])] });
328
+ }
301
329
  /**
302
330
  * 读一份文档;文件不存在时按"空 canonical 文档"造一份。
303
331
  * @param path - 文件路径。
@@ -729,17 +757,13 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
729
757
  const globalEnv = await this.readGlobalEnv();
730
758
  const global = this.readGlobal();
731
759
  const scan = this.scanComposition();
732
- let inputs = [...readFileSources(locations), ...cordisSourceResults(scan, locations)];
760
+ const managerOccupied = this.managerOccupiedNames();
761
+ let inputs = this.withManagerOccupied([...readFileSources(locations), ...cordisSourceResults(scan, locations)], managerOccupied);
733
762
  let preliminary = buildSnapshot(inputs, overlays, []);
734
763
  if (await this.migrateLegacySecretRows(preliminary.rows)) {
735
- inputs = [...readFileSources(locations), ...cordisSourceResults(scan, locations)];
764
+ inputs = this.withManagerOccupied([...readFileSources(locations), ...cordisSourceResults(scan, locations)], managerOccupied);
736
765
  preliminary = buildSnapshot(inputs, overlays, []);
737
766
  }
738
- this.toolControl.load(
739
- this.readToolSwitches(),
740
- global.injectionMode,
741
- preliminary.rows.map((row) => row.serverName)
742
- );
743
767
  const grouped = groupServerEnvNames(this.credentialRefNames(), preliminary.rows.map((row) => row.serverName));
744
768
  const infos = await Promise.all(preliminary.rows.map(
745
769
  async (row) => await this.secretInfoOf(row, grouped.get(row.serverName) ?? [])
@@ -748,6 +772,14 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
748
772
  (row, index) => this.mountRequestOf(row, globalEnv, global.injectGlobalEnvToStdio, infos[index])
749
773
  );
750
774
  const states = await this.mounts.sync(requests);
775
+ this.toolControl.load(
776
+ this.readToolSwitches(),
777
+ global.injectionMode,
778
+ // 已知集合要带上 manager 的 configured 名:否则 `foo` 与官方 `foo_extra` 并存时,
779
+ // 最长前缀匹配会退化成首个 `__` 切分,把官方工具误判成自有。
780
+ [.../* @__PURE__ */ new Set([...preliminary.rows.map((row) => row.serverName), ...managerOccupied])],
781
+ [...this.mounts.liveServerNames()]
782
+ );
751
783
  const secretRows = new Map(preliminary.rows.map((row, index) => [row.serverName, infos[index].rows]));
752
784
  const snapshot = buildSnapshot(inputs, overlays, states, secretRows);
753
785
  this.snapshot = {
@@ -809,6 +841,9 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
809
841
  if (declaration === void 0) {
810
842
  return failure("MCP_ADOPT_NOT_DECLARED", `\u7EC4\u5408\u5C42\u6CA1\u6709\u58F0\u660E\u540D\u4E3A ${JSON.stringify(serverName)} \u7684 MCP \u670D\u52A1\u5668`);
811
843
  }
844
+ if (declaration.adoptable === false) {
845
+ 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`);
846
+ }
812
847
  if (declaration.rowId === void 0) {
813
848
  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
849
  }
@@ -1054,10 +1089,10 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1054
1089
  }
1055
1090
  return { ...configs, tool_switches: switches };
1056
1091
  });
1057
- for (const client of [false, true]) {
1092
+ for (const kind of ["token", "client", "access"]) {
1058
1093
  try {
1059
- const fromRef = oauthRef(from, client);
1060
- const toRef = oauthRef(to, client);
1094
+ const fromRef = kind === "access" ? oauthAccessRef(from) : oauthRef(from, kind === "client");
1095
+ const toRef = kind === "access" ? oauthAccessRef(to) : oauthRef(to, kind === "client");
1061
1096
  if (String(fromRef) === String(toRef)) continue;
1062
1097
  const resolved = await this.hostCtx.credentials.resolve(fromRef);
1063
1098
  if (resolved !== void 0 && resolved.value !== "") await this.hostCtx.credentials.set(toRef, resolved.value);
@@ -1109,7 +1144,7 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1109
1144
  return cached;
1110
1145
  }
1111
1146
  try {
1112
- const response = await fetch(metadata.registrationEndpoint, {
1147
+ const response = await systemFetch()(metadata.registrationEndpoint, {
1113
1148
  method: "POST",
1114
1149
  headers: { "content-type": "application/json", accept: "application/json" },
1115
1150
  body: JSON.stringify({
@@ -1207,6 +1242,9 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1207
1242
  ...metadata.scopesSupported === void 0 || metadata.scopesSupported.length === 0 ? {} : { scope: metadata.scopesSupported.join(" ") }
1208
1243
  });
1209
1244
  void callback.then(async (result) => {
1245
+ if (result.iss !== void 0 && metadata.issuer !== void 0 && result.iss !== metadata.issuer) {
1246
+ throw new Error(`OAuth issuer mismatch: callback says ${JSON.stringify(result.iss)}, metadata says ${JSON.stringify(metadata.issuer)}`);
1247
+ }
1210
1248
  const token = await exchangeCode({
1211
1249
  tokenEndpoint: metadata.tokenEndpoint,
1212
1250
  code: result.code,
@@ -1215,9 +1253,13 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1215
1253
  redirectUri: result.redirectUri,
1216
1254
  ...client.clientSecret === void 0 ? {} : { clientSecret: client.clientSecret }
1217
1255
  });
1218
- await this.hostCtx.credentials.set(oauthRef(serverName), serializeToken(token));
1256
+ await writeToken(this.hostCtx.credentials, serverName, token);
1219
1257
  process.stderr.write(`dsh-mcp-ops: OAuth \u6388\u6743\u5B8C\u6210\uFF08${serverName}\uFF09\uFF0Ctoken \u5DF2\u5B58\u50A8
1220
1258
  `);
1259
+ await this.forceRestartOAuth(serverName).catch((error) => {
1260
+ process.stderr.write(`dsh-mcp-ops: OAuth \u6388\u6743\u540E\u91CD\u5EFA\u5931\u8D25\uFF08${serverName}\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}
1261
+ `);
1262
+ });
1221
1263
  }).catch((error) => {
1222
1264
  process.stderr.write(`dsh-mcp-ops: OAuth \u6388\u6743\u5931\u8D25\uFF08${serverName}\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}
1223
1265
  `);
@@ -1565,6 +1607,7 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1565
1607
  } catch {
1566
1608
  }
1567
1609
  }
1610
+ await clearToken(this.hostCtx.credentials, serverName);
1568
1611
  }
1569
1612
  for (const [envName, value] of Object.entries(row.spec.env)) {
1570
1613
  const ref = legacySecretRef(serverName, envName, value.value);
@@ -1822,6 +1865,32 @@ class McpOpsService extends (_a = TypertRemoteService, _list_dec = [Remote], _re
1822
1865
  await this.sync();
1823
1866
  return { ok: true, value: payload.value };
1824
1867
  }
1868
+ /**
1869
+ * 授权完成后强制重建**这一个**服务器的注册(忽略指纹)。
1870
+ *
1871
+ * 为什么需要显式重建:授权前若没有新鲜 token,`sync()` 会把该服务器记为 `failed` 且不注册;
1872
+ * 拿到 token 后只写凭据不会让"未注册"的服务器自动出现。这里重读一次行、重建挂载请求并
1873
+ * 走 `mounts.restart()`,随后再 `sync()` 刷新整份视图。
1874
+ *
1875
+ * @param serverName - 刚完成授权的服务器名。
1876
+ */
1877
+ async forceRestartOAuth(serverName) {
1878
+ const { locations, rows, overlays } = await this.readNow();
1879
+ const globalEnv = await this.readGlobalEnv();
1880
+ const global = this.readGlobal();
1881
+ const scan = this.scanComposition();
1882
+ const inputs = [...readFileSources(locations), ...cordisSourceResults(scan, locations)];
1883
+ const preliminary = buildSnapshot(inputs, overlays, []);
1884
+ const row = effectiveRow(preliminary.rows, serverName);
1885
+ if (row === void 0 || !row.enabled || row.occupiedByComposition) return;
1886
+ await this.mounts.restart(this.mountRequestOf(
1887
+ row,
1888
+ globalEnv,
1889
+ global.injectGlobalEnvToStdio,
1890
+ await this.secretInfoOf(row, serverEnvNamesOf(this.credentialRefNames(), serverName))
1891
+ ));
1892
+ this.snapshot = await this.sync();
1893
+ }
1825
1894
  async oauthStart(request) {
1826
1895
  await this.ready;
1827
1896
  const serverName = typeof request?.serverName === "string" ? request.serverName : "";
@@ -1874,7 +1943,7 @@ __decorateElement(_init, 1, "envSet", _envSet_dec, McpOpsService);
1874
1943
  __decorateElement(_init, 1, "oauthStart", _oauthStart_dec, McpOpsService);
1875
1944
  __decoratorMetadata(_init, McpOpsService);
1876
1945
  /** 需要的 Host 服务:缺任何一个即不激活。 */
1877
- __publicField(McpOpsService, "inject", ["credentials", "tools"]);
1946
+ __publicField(McpOpsService, "inject", ["credentials", "tools", "mcpManager"]);
1878
1947
  function failure(code, message) {
1879
1948
  return { ok: false, error: { code, message } };
1880
1949
  }
@@ -6,6 +6,7 @@ import { applyEntryPatches, entryListSchema } from "@deepseek-ai/cordis-plugin-i
6
6
  import { diagnostic } from "../files/mcp-json.js";
7
7
  import { readManagedRowIds } from "../files/patch-writer.js";
8
8
  const MCP_CLIENT_PACKAGE = "@deepseek-ai/dsh-mcp-client";
9
+ const MCP_MANAGER_PACKAGE = "@deepseek-ai/dsh-mcp-manager";
9
10
  const OWN_PACKAGE = "dsh-mcp-ops";
10
11
  const PROFILE_PATCH_FILENAME = "cordis.patch.yml";
11
12
  function ownPackageRoot() {
@@ -152,17 +153,37 @@ function declarationsOf(effective, managed) {
152
153
  const managedIds = new Set(managed.flatMap((entry) => entry.rowIds));
153
154
  const declarations = [];
154
155
  for (const row of effective) {
155
- if (row.name !== MCP_CLIENT_PACKAGE) continue;
156
- if (row.serverName === void 0) continue;
157
- declarations.push({
158
- serverName: row.serverName,
159
- ...row.id === void 0 ? {} : { rowId: row.id },
160
- ...row.config === void 0 ? {} : { config: row.config },
161
- path: row.path,
162
- disabled: row.disabled === true,
163
- hasJsExpr: row.hasJsExpr,
164
- managed: row.id !== void 0 && managedIds.has(row.id)
165
- });
156
+ if (row.name === MCP_CLIENT_PACKAGE) {
157
+ if (row.serverName === void 0) continue;
158
+ declarations.push({
159
+ serverName: row.serverName,
160
+ ...row.id === void 0 ? {} : { rowId: row.id },
161
+ ...row.config === void 0 ? {} : { config: row.config },
162
+ path: row.path,
163
+ disabled: row.disabled === true,
164
+ hasJsExpr: row.hasJsExpr,
165
+ managed: row.id !== void 0 && managedIds.has(row.id)
166
+ });
167
+ continue;
168
+ }
169
+ if (row.name !== MCP_MANAGER_PACKAGE) continue;
170
+ if (row.config === null || typeof row.config !== "object") continue;
171
+ const servers = row.config.servers;
172
+ if (servers === null || typeof servers !== "object") continue;
173
+ for (const [serverName, entry] of Object.entries(servers)) {
174
+ if (entry === null || typeof entry !== "object") continue;
175
+ declarations.push({
176
+ serverName,
177
+ ...row.id === void 0 ? {} : { rowId: row.id },
178
+ // 合成一条与 mcp-client 同形的 config,让视图能显示 transport/url/command。
179
+ config: { serverName, ...entry },
180
+ path: row.path,
181
+ disabled: row.disabled === true,
182
+ hasJsExpr: row.hasJsExpr || containsJsExpr(entry),
183
+ managed: false,
184
+ adoptable: false
185
+ });
186
+ }
166
187
  }
167
188
  return declarations;
168
189
  }
@@ -174,7 +195,7 @@ function cordisSourceResults(scan, locations) {
174
195
  const capabilities = {};
175
196
  for (const entry of mine) {
176
197
  capabilities[entry.serverName] = {
177
- adoptable: entry.rowId !== void 0 && !entry.hasJsExpr && !entry.managed,
198
+ adoptable: entry.adoptable !== false && entry.rowId !== void 0 && !entry.hasJsExpr && !entry.managed,
178
199
  adopted: entry.managed && entry.disabled
179
200
  };
180
201
  }
@@ -215,7 +236,7 @@ function specFromCordisConfig(declaration) {
215
236
  return out;
216
237
  };
217
238
  const timeout = typeof record.toolCallTimeoutMs === "number" ? record.toolCallTimeoutMs : void 0;
218
- const known = /* @__PURE__ */ new Set(["transport", "serverName", "command", "args", "cwd", "env", "url", "headers", "toolCallTimeoutMs"]);
239
+ const known = /* @__PURE__ */ new Set(["transport", "serverName", "command", "args", "cwd", "env", "url", "headers", "toolCallTimeoutMs", "startupTimeoutMs", "closeTimeoutMs", "reconnect", "enabled"]);
219
240
  const extraKeys = Object.keys(record).filter((key) => !known.has(key));
220
241
  return {
221
242
  serverName: declaration.serverName,
@@ -235,6 +256,7 @@ function specFromCordisConfig(declaration) {
235
256
  }
236
257
  export {
237
258
  MCP_CLIENT_PACKAGE,
259
+ MCP_MANAGER_PACKAGE,
238
260
  OWN_PACKAGE,
239
261
  PROFILE_PATCH_FILENAME,
240
262
  containsJsExpr,
@@ -0,0 +1,79 @@
1
+ import { readFileSync } from "node:fs";
2
+ import tls from "node:tls";
3
+ const OS_CA_FILES = [
4
+ "/etc/ssl/cert.pem",
5
+ "/etc/ssl/certs/ca-certificates.crt",
6
+ "/etc/pki/tls/certs/ca-bundle.crt",
7
+ "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"
8
+ ];
9
+ function splitPem(text) {
10
+ return text.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? [];
11
+ }
12
+ function systemCaCertificates() {
13
+ const certificates = [];
14
+ if (typeof tls.getCACertificates === "function") {
15
+ try {
16
+ certificates.push(...tls.getCACertificates("system") ?? []);
17
+ } catch {
18
+ }
19
+ }
20
+ for (const file of OS_CA_FILES) {
21
+ try {
22
+ certificates.push(...splitPem(readFileSync(file, "utf8")));
23
+ } catch {
24
+ }
25
+ }
26
+ return [...new Set(certificates)];
27
+ }
28
+ let trustState;
29
+ function ensureSystemCaTrust(options = {}) {
30
+ if (trustState !== void 0 && options.refresh !== true) return trustState;
31
+ const canSetDefault = typeof tls.getCACertificates === "function" && typeof tls.setDefaultCACertificates === "function";
32
+ if (!canSetDefault) {
33
+ trustState = { applied: false, added: 0, system: 0, reason: "node-api-unavailable" };
34
+ return trustState;
35
+ }
36
+ let defaults;
37
+ try {
38
+ defaults = tls.getCACertificates("default") ?? [];
39
+ } catch {
40
+ trustState = { applied: false, added: 0, system: 0, reason: "default-store-unreadable" };
41
+ return trustState;
42
+ }
43
+ let system;
44
+ try {
45
+ system = options.systemCertificates ?? systemCaCertificates();
46
+ } catch {
47
+ system = [];
48
+ }
49
+ if (system.length === 0) {
50
+ trustState = { applied: false, added: 0, system: 0, reason: "no-system-ca" };
51
+ return trustState;
52
+ }
53
+ const merged = [.../* @__PURE__ */ new Set([...defaults, ...system])];
54
+ if (merged.length === defaults.length) {
55
+ trustState = { applied: false, added: 0, system: system.length, reason: "already-trusted" };
56
+ return trustState;
57
+ }
58
+ try {
59
+ tls.setDefaultCACertificates(merged);
60
+ } catch {
61
+ trustState = { applied: false, added: 0, system: system.length, reason: "set-failed" };
62
+ return trustState;
63
+ }
64
+ trustState = { applied: true, added: merged.length - defaults.length, system: system.length };
65
+ return trustState;
66
+ }
67
+ function systemFetch() {
68
+ ensureSystemCaTrust();
69
+ return fetch;
70
+ }
71
+ function resetSystemCaTrustState() {
72
+ trustState = void 0;
73
+ }
74
+ export {
75
+ ensureSystemCaTrust,
76
+ resetSystemCaTrustState,
77
+ systemCaCertificates,
78
+ systemFetch
79
+ };