mcpSyncService.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. /* eslint-disable max-lines -- MCP 同步服务集中维护用户目录读写、远端导入和 filesystem 路径改写,拆分会增加远端配置同步回归面。 */
  2. import { createHash } from "node:crypto";
  3. import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
  4. import { homedir } from "node:os";
  5. import { basename, dirname, join, posix, win32 } from "node:path";
  6. import type {
  7. LoadCliMcpFromUserDirectoryRequest,
  8. LoadCliMcpFromUserDirectoryResult,
  9. McpScope,
  10. McpServerConfig,
  11. McpSyncCandidate,
  12. McpSyncExportedServer,
  13. McpSyncImportResult,
  14. McpSyncRemoteStatus,
  15. McpSyncSource,
  16. NativeMcpServerRecord,
  17. SaveCliMcpToUserDirectoryRequest,
  18. SettingsDirectoryLocation,
  19. SettingsDirectorySource,
  20. } from "@zcode/shared";
  21. import type { IMcpSyncService } from "./mcpSync.js";
  22. import { checkRemoteSyncDirectoryWriteAccess } from "../remote-sync/remoteSyncWriteAccess.js";
  23. type McpConfigKeyName = "mcp.servers" | "mcpServers";
  24. interface DirectoryMcpDescriptor {
  25. source: McpSyncSource;
  26. directorySource: SettingsDirectorySource;
  27. userConfigDirSegments: string[];
  28. workspaceConfigDirSegments: string[];
  29. fileName: string;
  30. configKeyName: McpConfigKeyName;
  31. }
  32. interface UserMcpRecord {
  33. name: string;
  34. config: McpServerConfig;
  35. enabled: boolean;
  36. source: McpSyncSource;
  37. path: string;
  38. }
  39. const ZCODE_MCP_DESCRIPTOR: DirectoryMcpDescriptor = {
  40. source: "zcode",
  41. directorySource: "zcode",
  42. userConfigDirSegments: [".zcode", "cli"],
  43. workspaceConfigDirSegments: [".zcode"],
  44. fileName: "config.json",
  45. configKeyName: "mcp.servers",
  46. };
  47. const AGENTS_MCP_DESCRIPTOR: DirectoryMcpDescriptor = {
  48. source: "agents",
  49. directorySource: "agents",
  50. userConfigDirSegments: [".agents"],
  51. workspaceConfigDirSegments: [".agents"],
  52. fileName: "mcp.json",
  53. configKeyName: "mcpServers",
  54. };
  55. const ENABLED_KEY = "enabled";
  56. // 历史遗留:桌面端早期把停用状态写成 enable,而 CLI 契约字段(contracts McpServerConfigBase)
  57. // 一直是 enabled,导致同一条 server 出现两套口径、停用后仍被 agent 拉起。
  58. // 现在读写逻辑一律只认 enabled,这里只保留一次性迁移;存量配置清空后整块删除。
  59. const LEGACY_ENABLE_KEY = "enable";
  60. const SECRET_CONFIG_FILE_MODE = 0o600;
  61. const DIRECTORY_MCP_DESCRIPTORS: readonly DirectoryMcpDescriptor[] = [
  62. ZCODE_MCP_DESCRIPTOR,
  63. AGENTS_MCP_DESCRIPTOR,
  64. ];
  65. export interface McpSyncServiceDependencies {
  66. /**
  67. * MCP server 运行态状态检查的执行面。真实 connect/listTools 必须发生在
  68. * agent 进程(workspace 的 PATH/cwd 环境),host 侧没有可替代实现;无该依赖的
  69. * 构造(纯目录同步用途/单测)调用 listWorkspaceMcpServerStatuses 会显式抛错。
  70. */
  71. listMcpServerStatuses?: IMcpSyncService["listWorkspaceMcpServerStatuses"];
  72. }
  73. export function createMcpSyncService(
  74. dependencies: McpSyncServiceDependencies = {},
  75. ): IMcpSyncService {
  76. return {
  77. async loadMcpFromUserDirectory(request) {
  78. return loadMcpFromUserDirectory(request);
  79. },
  80. async listWorkspaceMcpServerStatuses(params) {
  81. if (!dependencies.listMcpServerStatuses) {
  82. throw new Error("MCP server status listing is unavailable in this runtime");
  83. }
  84. return dependencies.listMcpServerStatuses(params);
  85. },
  86. async saveMcpToUserDirectory(payload) {
  87. await saveMcpToUserDirectory(payload);
  88. },
  89. async listLocalUserMcpCandidates() {
  90. const localHomeDir = resolveUserHomeDir();
  91. return {
  92. candidates: (await collectEffectiveUserMcpRecords()).map(
  93. recordToCandidate,
  94. ),
  95. localHomeDir,
  96. };
  97. },
  98. async listRemoteUserMcpStatuses(params) {
  99. const remoteHomeDir = resolveUserHomeDir();
  100. const existingByName = await collectEffectiveUserMcpRecordByName();
  101. return {
  102. remoteHomeDir,
  103. statuses: params.names.map((name): McpSyncRemoteStatus => {
  104. const existing = existingByName.get(normalizeMcpNameKey(name));
  105. return existing
  106. ? { name, exists: true, path: existing.path }
  107. : { name, exists: false };
  108. }),
  109. };
  110. },
  111. async exportMcpServers(params) {
  112. const candidates = (await collectEffectiveUserMcpRecords()).map(
  113. recordToCandidate,
  114. );
  115. const candidateById = new Map(
  116. candidates.map((candidate) => [candidate.id, candidate]),
  117. );
  118. return {
  119. localHomeDir: resolveUserHomeDir(),
  120. servers: params.serverIds.map((id): McpSyncExportedServer => {
  121. const candidate = candidateById.get(id);
  122. if (!candidate) {
  123. throw new Error(`mcp sync candidate not found: ${id}`);
  124. }
  125. return {
  126. id: candidate.id,
  127. name: candidate.name,
  128. config: cloneMcpConfig(candidate.config),
  129. enabled: candidate.enabled,
  130. source: candidate.source,
  131. path: candidate.path,
  132. };
  133. }),
  134. };
  135. },
  136. async checkRemoteUserMcpWriteAccess() {
  137. return checkRemoteSyncDirectoryWriteAccess(dirname(getUserZcodeMcpConfigPath()));
  138. },
  139. async importMcpServers(params) {
  140. if (params.overwrite) {
  141. throw new Error("mcp sync overwrite is not supported");
  142. }
  143. return await importMcpServers(params);
  144. },
  145. };
  146. }
  147. function resolveUserHomeDir(): string {
  148. return (
  149. process.env.HOME?.trim() || process.env.USERPROFILE?.trim() || homedir()
  150. );
  151. }
  152. function buildDirectoryConfigPath(
  153. descriptor: DirectoryMcpDescriptor,
  154. scope: Exclude<McpScope, "common">,
  155. workspacePath?: string,
  156. ): string {
  157. const baseDir = scope === "user" ? resolveUserHomeDir() : workspacePath;
  158. if (!baseDir) {
  159. throw new Error(
  160. `Missing workspace path for ${descriptor.directorySource} workspace MCP config`,
  161. );
  162. }
  163. const segments =
  164. scope === "user"
  165. ? descriptor.userConfigDirSegments
  166. : descriptor.workspaceConfigDirSegments;
  167. return join(baseDir, ...segments, descriptor.fileName);
  168. }
  169. function buildUserConfigPath(descriptor: DirectoryMcpDescriptor): string {
  170. return buildDirectoryConfigPath(descriptor, "user");
  171. }
  172. function getUserZcodeMcpConfigPath(): string {
  173. return buildUserConfigPath(ZCODE_MCP_DESCRIPTOR);
  174. }
  175. function buildDirectoryMcpLocation(
  176. descriptor: DirectoryMcpDescriptor,
  177. scope: Exclude<McpScope, "common">,
  178. workspacePath?: string,
  179. ): SettingsDirectoryLocation {
  180. const filePath = buildDirectoryConfigPath(descriptor, scope, workspacePath);
  181. return {
  182. source: descriptor.directorySource,
  183. scope: scope === "workspace" ? "project" : "user",
  184. directoryPath: dirname(filePath),
  185. ...(workspacePath ? { projectPath: workspacePath } : {}),
  186. };
  187. }
  188. function findDescriptorByLocation(
  189. location: SettingsDirectoryLocation,
  190. ): DirectoryMcpDescriptor {
  191. const descriptor = DIRECTORY_MCP_DESCRIPTORS.find(
  192. (item) => item.directorySource === location.source,
  193. );
  194. if (!descriptor) {
  195. throw new Error(
  196. `Unsupported MCP settings directory source: ${location.source}`,
  197. );
  198. }
  199. return descriptor;
  200. }
  201. async function collectEffectiveUserMcpRecords(): Promise<UserMcpRecord[]> {
  202. const zcodeRecords = await readUserMcpRecordsFromFile(ZCODE_MCP_DESCRIPTOR);
  203. if (zcodeRecords.length > 0) {
  204. return sortMcpRecords(zcodeRecords);
  205. }
  206. return sortMcpRecords(
  207. await readUserMcpRecordsFromFile(AGENTS_MCP_DESCRIPTOR),
  208. );
  209. }
  210. async function collectEffectiveUserMcpRecordByName(): Promise<
  211. Map<string, UserMcpRecord>
  212. > {
  213. const result = new Map<string, UserMcpRecord>();
  214. for (const record of await collectEffectiveUserMcpRecords()) {
  215. const nameKey = normalizeMcpNameKey(record.name);
  216. if (!result.has(nameKey)) {
  217. result.set(nameKey, record);
  218. }
  219. }
  220. return result;
  221. }
  222. async function loadMcpFromUserDirectory(
  223. request?: LoadCliMcpFromUserDirectoryRequest,
  224. ): Promise<LoadCliMcpFromUserDirectoryResult> {
  225. const servers: NativeMcpServerRecord[] = [];
  226. if (request?.workspacePath) {
  227. servers.push(
  228. ...(await readDirectoryServersFromPreferredSources(
  229. "workspace",
  230. request.workspacePath,
  231. )),
  232. );
  233. }
  234. servers.push(
  235. ...(await readDirectoryServersFromPreferredSources(
  236. "user",
  237. request?.workspacePath,
  238. )),
  239. );
  240. return { servers };
  241. }
  242. async function saveMcpToUserDirectory(
  243. payload: SaveCliMcpToUserDirectoryRequest,
  244. ): Promise<void> {
  245. if (payload.action === "set-enabled") {
  246. if (typeof payload.enabled !== "boolean") {
  247. throw new Error("Missing enabled value for MCP set-enabled action");
  248. }
  249. const scope: Exclude<McpScope, "common"> = payload.projectPath
  250. ? "workspace"
  251. : "user";
  252. const location =
  253. payload.location ??
  254. buildDirectoryMcpLocation(
  255. ZCODE_MCP_DESCRIPTOR,
  256. scope,
  257. payload.projectPath,
  258. );
  259. await writeServerEnabledToFile(
  260. findDescriptorByLocation(location),
  261. location,
  262. payload.name,
  263. payload.enabled,
  264. );
  265. await cleanupLegacyMcpEnabledOverride(location, payload.name);
  266. return;
  267. }
  268. const scope: Exclude<McpScope, "common"> = payload.projectPath
  269. ? "workspace"
  270. : "user";
  271. const existingServers = await readDirectoryServersFromFile(
  272. ZCODE_MCP_DESCRIPTOR,
  273. scope,
  274. payload.projectPath,
  275. );
  276. const nextServers = Object.fromEntries(
  277. existingServers.map((server) => [
  278. server.name,
  279. server.config as Record<string, unknown>,
  280. ]),
  281. );
  282. if (payload.action === "upsert") {
  283. if (!payload.config) {
  284. throw new Error("Missing MCP config for upsert action");
  285. }
  286. nextServers[payload.name] = payload.config as Record<string, unknown>;
  287. } else {
  288. delete nextServers[payload.name];
  289. }
  290. await writeZCodeServersToFile(scope, nextServers, payload.projectPath);
  291. }
  292. function sortMcpRecords(records: UserMcpRecord[]): UserMcpRecord[] {
  293. return records.sort((left, right) => left.name.localeCompare(right.name));
  294. }
  295. async function readDirectoryServersFromPreferredSources(
  296. scope: Exclude<McpScope, "common">,
  297. workspacePath?: string,
  298. ): Promise<NativeMcpServerRecord[]> {
  299. const zcodeServers = await readDirectoryServersFromFile(
  300. ZCODE_MCP_DESCRIPTOR,
  301. scope,
  302. workspacePath,
  303. );
  304. if (zcodeServers.length > 0) {
  305. return zcodeServers;
  306. }
  307. return readDirectoryServersFromFile(
  308. AGENTS_MCP_DESCRIPTOR,
  309. scope,
  310. workspacePath,
  311. );
  312. }
  313. async function readDirectoryServersFromFile(
  314. descriptor: DirectoryMcpDescriptor,
  315. scope: Exclude<McpScope, "common">,
  316. workspacePath?: string,
  317. ): Promise<NativeMcpServerRecord[]> {
  318. const filePath = buildDirectoryConfigPath(descriptor, scope, workspacePath);
  319. const parsed = await readJsonObject(filePath);
  320. if (!parsed) {
  321. return [];
  322. }
  323. const serverMap = await readServerMapWithLegacyMigration(
  324. filePath,
  325. parsed,
  326. descriptor.configKeyName,
  327. );
  328. const location = buildDirectoryMcpLocation(descriptor, scope, workspacePath);
  329. return Object.entries(serverMap).map(([name, config]) => ({
  330. source: "zcodeagentmcp",
  331. scope,
  332. name,
  333. config: config as McpServerConfig,
  334. enabled: readServerEnabled(config),
  335. projectPath: scope === "workspace" ? workspacePath : undefined,
  336. location,
  337. file: {
  338. format: "json",
  339. filePath,
  340. },
  341. }));
  342. }
  343. async function writeZCodeServersToFile(
  344. scope: Exclude<McpScope, "common">,
  345. servers: Record<string, Record<string, unknown>>,
  346. workspacePath?: string,
  347. ): Promise<void> {
  348. const filePath = buildDirectoryConfigPath(
  349. ZCODE_MCP_DESCRIPTOR,
  350. scope,
  351. workspacePath,
  352. );
  353. const current = (await readJsonObject(filePath)) ?? {};
  354. const next = writeServerMapToJson(
  355. current,
  356. ZCODE_MCP_DESCRIPTOR.configKeyName,
  357. servers,
  358. );
  359. await writeTextAtomic(filePath, `${JSON.stringify(next, null, 2)}\n`);
  360. }
  361. async function readUserCliConfig(): Promise<Record<string, unknown>> {
  362. return (await readJsonObject(getUserZcodeMcpConfigPath())) ?? {};
  363. }
  364. async function writeUserCliConfig(
  365. config: Record<string, unknown>,
  366. ): Promise<void> {
  367. await writeTextAtomic(
  368. getUserZcodeMcpConfigPath(),
  369. `${JSON.stringify(config, null, 2)}\n`,
  370. );
  371. }
  372. function removeLegacyMcpEnabledOverride(
  373. config: Record<string, unknown>,
  374. location: SettingsDirectoryLocation,
  375. name: string,
  376. ): { config: Record<string, unknown>; changed: boolean } {
  377. if (!isRecord(config.mcp) || !isRecord(config.mcp[location.directoryPath])) {
  378. return { config, changed: false };
  379. }
  380. const mcpConfig = { ...config.mcp };
  381. const pathConfig = {
  382. ...(mcpConfig[location.directoryPath] as Record<string, unknown>),
  383. };
  384. if (!(name in pathConfig)) {
  385. return { config, changed: false };
  386. }
  387. delete pathConfig[name];
  388. if (Object.keys(pathConfig).length > 0) {
  389. mcpConfig[location.directoryPath] = pathConfig;
  390. } else {
  391. delete mcpConfig[location.directoryPath];
  392. }
  393. return {
  394. config: {
  395. ...config,
  396. mcp: mcpConfig,
  397. },
  398. changed: true,
  399. };
  400. }
  401. async function cleanupLegacyMcpEnabledOverride(
  402. location: SettingsDirectoryLocation,
  403. name: string,
  404. ): Promise<void> {
  405. const userConfig = await readUserCliConfig();
  406. const result = removeLegacyMcpEnabledOverride(userConfig, location, name);
  407. if (result.changed) {
  408. await writeUserCliConfig(result.config);
  409. }
  410. }
  411. async function writeServerEnabledToFile(
  412. descriptor: DirectoryMcpDescriptor,
  413. location: SettingsDirectoryLocation,
  414. name: string,
  415. enabled: boolean,
  416. ): Promise<void> {
  417. const scope: Exclude<McpScope, "common"> =
  418. location.scope === "project" ? "workspace" : "user";
  419. const workspacePath =
  420. scope === "workspace" ? location.projectPath : undefined;
  421. const filePath = buildDirectoryConfigPath(descriptor, scope, workspacePath);
  422. const current = (await readJsonObject(filePath)) ?? {};
  423. const serverMap = readServerMapFromJson(current, descriptor.configKeyName);
  424. const currentServer = serverMap[name];
  425. if (!isRecord(currentServer)) {
  426. return;
  427. }
  428. // MCP 自身已有 mcp.servers/mcpServers 结构;禁用状态写在 server 配置对象内,
  429. // 避免把目录路径写到 mcp 顶层后和真实 MCP 配置混在一起。
  430. const nextServerMap = {
  431. ...serverMap,
  432. [name]: setServerEnabled(
  433. currentServer as McpServerConfig,
  434. enabled,
  435. ) as Record<string, unknown>,
  436. };
  437. let next = writeServerMapToJson(
  438. current,
  439. descriptor.configKeyName,
  440. nextServerMap,
  441. );
  442. const legacyCleanup = removeLegacyMcpEnabledOverride(next, location, name);
  443. if (legacyCleanup.changed) {
  444. next = legacyCleanup.config;
  445. }
  446. await writeTextAtomic(filePath, `${JSON.stringify(next, null, 2)}\n`);
  447. }
  448. async function readUserMcpRecordsFromFile(
  449. descriptor: DirectoryMcpDescriptor,
  450. ): Promise<UserMcpRecord[]> {
  451. const filePath = buildUserConfigPath(descriptor);
  452. const parsed = await readJsonObject(filePath);
  453. if (!parsed) {
  454. return [];
  455. }
  456. const serverMap = await readServerMapWithLegacyMigration(
  457. filePath,
  458. parsed,
  459. descriptor.configKeyName,
  460. );
  461. return Object.entries(serverMap).map(([name, config]) => ({
  462. name,
  463. config: config as McpServerConfig,
  464. enabled: readServerEnabled(config),
  465. source: descriptor.source,
  466. path: filePath,
  467. }));
  468. }
  469. function recordToCandidate(record: UserMcpRecord): McpSyncCandidate {
  470. return {
  471. id: createCandidateId(record),
  472. name: record.name,
  473. config: cloneMcpConfig(record.config),
  474. enabled: record.enabled,
  475. source: record.source,
  476. path: record.path,
  477. };
  478. }
  479. function createCandidateId(record: UserMcpRecord): string {
  480. return createHash("sha256")
  481. .update(`${record.source}:${record.path}:${record.name}`)
  482. .digest("hex");
  483. }
  484. function normalizeMcpNameKey(name: string): string {
  485. return name.trim().toLowerCase();
  486. }
  487. function readServerEnabled(config: Record<string, unknown>): boolean {
  488. return config[ENABLED_KEY] !== false;
  489. }
  490. function setServerEnabled(
  491. config: McpServerConfig,
  492. enabled: boolean,
  493. ): McpServerConfig {
  494. // 启用是默认态,不落盘冗余字段;同时清掉可能残留的 legacy enable,
  495. // 避免再产出 enable:false + enabled:true 这类自相矛盾的配置。
  496. const {
  497. [LEGACY_ENABLE_KEY]: _legacyEnable,
  498. [ENABLED_KEY]: _enabled,
  499. ...rest
  500. } = config;
  501. if (enabled) {
  502. return rest;
  503. }
  504. return { ...rest, [ENABLED_KEY]: false };
  505. }
  506. function migrateLegacyEnableFlag(
  507. serverMap: Record<string, Record<string, unknown>>,
  508. ): { servers: Record<string, Record<string, unknown>>; changed: boolean } {
  509. let changed = false;
  510. const migrated: Record<string, Record<string, unknown>> = {};
  511. for (const [name, config] of Object.entries(serverMap)) {
  512. if (!isRecord(config) || !(LEGACY_ENABLE_KEY in config)) {
  513. migrated[name] = config;
  514. continue;
  515. }
  516. changed = true;
  517. // 两个字段冲突时以「停用」为准:桌面端写 enable:false 时不会清理外部导入残留的
  518. // enabled:true,若按 enabled 取值会把用户关掉的 server 重新拉起。
  519. const disabled =
  520. config[LEGACY_ENABLE_KEY] === false || config[ENABLED_KEY] === false;
  521. migrated[name] = setServerEnabled(
  522. config as McpServerConfig,
  523. !disabled,
  524. ) as Record<string, unknown>;
  525. }
  526. return { servers: migrated, changed };
  527. }
  528. /**
  529. * 读取 server map,顺带把存量 enable 就地折叠成 enabled 并落盘。
  530. * 没有残留字段时不写文件,保证幂等;写盘失败不阻断读取,内存结果已是正确口径,下次加载会重试。
  531. */
  532. async function readServerMapWithLegacyMigration(
  533. filePath: string,
  534. parsed: Record<string, unknown>,
  535. configKeyName: McpConfigKeyName,
  536. ): Promise<Record<string, Record<string, unknown>>> {
  537. const migration = migrateLegacyEnableFlag(
  538. readServerMapFromJson(parsed, configKeyName),
  539. );
  540. if (!migration.changed) {
  541. return migration.servers;
  542. }
  543. try {
  544. const next = writeServerMapToJson(parsed, configKeyName, migration.servers);
  545. await writeTextAtomic(filePath, `${JSON.stringify(next, null, 2)}\n`);
  546. } catch (error) {
  547. console.warn(
  548. "[mcp-sync] legacy enable migration failed:",
  549. filePath,
  550. formatErrorMessage(error),
  551. );
  552. }
  553. return migration.servers;
  554. }
  555. function readServerMapFromJson(
  556. parsed: Record<string, unknown>,
  557. configKeyName: McpConfigKeyName,
  558. ): Record<string, Record<string, unknown>> {
  559. if (configKeyName === "mcp.servers") {
  560. const mcp = parsed.mcp;
  561. if (!isRecord(mcp)) {
  562. return {};
  563. }
  564. const servers = mcp.servers;
  565. return isRecord(servers)
  566. ? (servers as Record<string, Record<string, unknown>>)
  567. : {};
  568. }
  569. const rawServerMap = parsed[configKeyName];
  570. return isRecord(rawServerMap)
  571. ? (rawServerMap as Record<string, Record<string, unknown>>)
  572. : {};
  573. }
  574. function writeServerMapToJson(
  575. current: Record<string, unknown>,
  576. configKeyName: McpConfigKeyName,
  577. servers: Record<string, Record<string, unknown>>,
  578. ): Record<string, unknown> {
  579. if (configKeyName !== "mcp.servers") {
  580. return {
  581. ...current,
  582. [configKeyName]: servers,
  583. };
  584. }
  585. const currentMcp = isRecord(current.mcp) ? current.mcp : {};
  586. return {
  587. ...current,
  588. mcp: {
  589. ...currentMcp,
  590. servers,
  591. },
  592. };
  593. }
  594. async function importMcpServers(params: {
  595. servers: McpSyncExportedServer[];
  596. localHomeDir: string;
  597. localWorkspacePath?: string;
  598. remoteWorkspacePath?: string;
  599. }): Promise<McpSyncImportResult> {
  600. const targetPath = getUserZcodeMcpConfigPath();
  601. const current = (await readJsonObject(targetPath)) ?? {};
  602. const targetServers = readServerMapFromJson(
  603. current,
  604. ZCODE_MCP_DESCRIPTOR.configKeyName,
  605. );
  606. const existingByName = await collectEffectiveUserMcpRecordByName();
  607. const results: McpSyncImportResult["results"] = [];
  608. let changed = false;
  609. for (const server of params.servers) {
  610. const nameKey = normalizeMcpNameKey(server.name);
  611. const existingTarget = targetServers[server.name];
  612. if (existingTarget) {
  613. results.push({ name: server.name, status: "skipped", path: targetPath });
  614. continue;
  615. }
  616. const existing = existingByName.get(nameKey);
  617. if (existing) {
  618. results.push({
  619. name: server.name,
  620. status: "skipped",
  621. path: existing.path,
  622. });
  623. continue;
  624. }
  625. try {
  626. const rewrittenConfig = rewriteFilesystemMcpConfig(
  627. server.name,
  628. setServerEnabled(cloneMcpConfig(server.config), server.enabled),
  629. {
  630. localHomeDir: params.localHomeDir,
  631. localWorkspacePath: params.localWorkspacePath,
  632. remoteHomeDir: resolveUserHomeDir(),
  633. remoteWorkspacePath: params.remoteWorkspacePath,
  634. },
  635. );
  636. targetServers[server.name] = rewrittenConfig as Record<string, unknown>;
  637. existingByName.set(nameKey, {
  638. name: server.name,
  639. config: rewrittenConfig,
  640. enabled: server.enabled,
  641. source: "zcode",
  642. path: targetPath,
  643. });
  644. results.push({ name: server.name, status: "synced", path: targetPath });
  645. changed = true;
  646. } catch (error) {
  647. results.push({
  648. name: server.name,
  649. status: "failed",
  650. path: targetPath,
  651. error: error instanceof Error ? error.message : String(error),
  652. });
  653. }
  654. }
  655. if (changed) {
  656. await writeTextAtomic(
  657. targetPath,
  658. `${JSON.stringify(writeServerMapToJson(current, ZCODE_MCP_DESCRIPTOR.configKeyName, targetServers), null, 2)}\n`,
  659. );
  660. }
  661. return { results };
  662. }
  663. function rewriteFilesystemMcpConfig(
  664. name: string,
  665. config: McpServerConfig,
  666. paths: {
  667. localHomeDir: string;
  668. localWorkspacePath?: string;
  669. remoteHomeDir: string;
  670. remoteWorkspacePath?: string;
  671. },
  672. ): McpServerConfig {
  673. if (!isStdioMcpConfig(config) || !isFilesystemMcpServer(name, config)) {
  674. return config;
  675. }
  676. if (!Array.isArray(config.args)) {
  677. return config;
  678. }
  679. return {
  680. ...config,
  681. args: config.args.map((arg) => rewritePathArgForRemote(arg, paths)),
  682. };
  683. }
  684. function isStdioMcpConfig(config: McpServerConfig): boolean {
  685. const type =
  686. typeof config.type === "string" ? config.type.trim().toLowerCase() : "";
  687. if (!type && typeof config.command === "string" && config.command.trim()) {
  688. return true;
  689. }
  690. return type === "stdio";
  691. }
  692. function isFilesystemMcpServer(name: string, config: McpServerConfig): boolean {
  693. const normalizedName = name.trim().toLowerCase();
  694. if (
  695. normalizedName === "filesystem" ||
  696. normalizedName === "file-system" ||
  697. normalizedName === "fs"
  698. ) {
  699. return true;
  700. }
  701. const haystack = [
  702. config.command,
  703. ...(Array.isArray(config.args) ? config.args : []),
  704. ]
  705. .filter((value): value is string => typeof value === "string")
  706. .join(" ")
  707. .toLowerCase();
  708. return (
  709. haystack.includes("@modelcontextprotocol/server-filesystem") ||
  710. haystack.includes("mcp-server-filesystem")
  711. );
  712. }
  713. function rewritePathArgForRemote(
  714. arg: string,
  715. paths: {
  716. localHomeDir: string;
  717. localWorkspacePath?: string;
  718. remoteHomeDir: string;
  719. remoteWorkspacePath?: string;
  720. },
  721. ): string {
  722. const workspaceRelative = getRelativePathIfWithin(
  723. paths.localWorkspacePath,
  724. arg,
  725. );
  726. if (workspaceRelative !== null && paths.remoteWorkspacePath?.trim()) {
  727. return joinRemotePath(paths.remoteWorkspacePath, workspaceRelative);
  728. }
  729. const homeRelative = getRelativePathIfWithin(paths.localHomeDir, arg);
  730. if (homeRelative !== null) {
  731. return joinRemotePath(paths.remoteHomeDir, homeRelative);
  732. }
  733. return arg;
  734. }
  735. function getRelativePathIfWithin(
  736. basePath: string | undefined,
  737. candidatePath: string,
  738. ): string | null {
  739. if (!basePath?.trim()) {
  740. return null;
  741. }
  742. const base = normalizeComparablePath(basePath);
  743. const candidate = normalizeComparablePath(candidatePath);
  744. if (!base || !candidate) {
  745. return null;
  746. }
  747. const baseValue = base.caseInsensitive
  748. ? base.value.toLowerCase()
  749. : base.value;
  750. const candidateValue = base.caseInsensitive
  751. ? candidate.value.toLowerCase()
  752. : candidate.value;
  753. if (candidateValue === baseValue) {
  754. return "";
  755. }
  756. const prefix = baseValue.endsWith("/") ? baseValue : `${baseValue}/`;
  757. if (!candidateValue.startsWith(prefix)) {
  758. return null;
  759. }
  760. return candidate.value.slice(prefix.length);
  761. }
  762. function normalizeComparablePath(
  763. rawPath: string,
  764. ): { value: string; caseInsensitive: boolean } | null {
  765. const trimmed = rawPath.trim();
  766. if (!trimmed) {
  767. return null;
  768. }
  769. const isWindowsPath =
  770. /^[a-zA-Z]:[\\/]/u.test(trimmed) || trimmed.startsWith("\\\\");
  771. const isPosixPath = trimmed.startsWith("/");
  772. if (!isWindowsPath && !isPosixPath) {
  773. return null;
  774. }
  775. let value = trimmed.replaceAll("\\", "/");
  776. value = value.replace(/\/+$/u, "");
  777. if (value === "") {
  778. value = "/";
  779. }
  780. return {
  781. value,
  782. caseInsensitive: isWindowsPath,
  783. };
  784. }
  785. function joinRemotePath(remoteBasePath: string, relativePath: string): string {
  786. if (!relativePath) {
  787. return remoteBasePath;
  788. }
  789. const segments = relativePath.split(/[\\/]+/u).filter(Boolean);
  790. // MCP 同步运行在本机进程里,但 remoteWorkspacePath 描述的是远端主机路径。
  791. // 不能用 process.platform 决定拼接风格,否则 Windows 客户端同步到 Linux/WSL 时会把 /srv/... 写成 \srv\...。
  792. const normalizedBasePath = remoteBasePath.trim();
  793. if (normalizedBasePath.startsWith("/")) {
  794. return posix.join(normalizedBasePath.replaceAll("\\", "/"), ...segments);
  795. }
  796. if (
  797. /^[a-zA-Z]:[\\/]/u.test(normalizedBasePath) ||
  798. normalizedBasePath.startsWith("\\\\")
  799. ) {
  800. return win32.join(normalizedBasePath, ...segments);
  801. }
  802. return posix.join(normalizedBasePath.replaceAll("\\", "/"), ...segments);
  803. }
  804. function cloneMcpConfig(config: McpServerConfig): McpServerConfig {
  805. return JSON.parse(JSON.stringify(config)) as McpServerConfig;
  806. }
  807. function isRecord(value: unknown): value is Record<string, unknown> {
  808. return typeof value === "object" && value !== null && !Array.isArray(value);
  809. }
  810. async function readJsonObject(
  811. filePath: string,
  812. ): Promise<Record<string, unknown> | null> {
  813. let raw: string;
  814. try {
  815. raw = await readFile(filePath, "utf-8");
  816. } catch (error) {
  817. if (isErrnoException(error) && error.code === "ENOENT") {
  818. return null;
  819. }
  820. throw new Error(
  821. `无法读取 MCP 配置文件 ${filePath}: ${formatErrorMessage(error)}`,
  822. );
  823. }
  824. let parsed: unknown;
  825. try {
  826. parsed = JSON.parse(raw) as unknown;
  827. } catch (error) {
  828. // 远端 MCP 导入必须先确认现有 config.json 可读可合并;
  829. // JSON 损坏时如果当作空对象继续写,会静默覆盖 provider、MCP 和 secret 配置。
  830. throw new Error(
  831. `无法解析 MCP 配置文件 ${filePath}: ${formatErrorMessage(error)}`,
  832. );
  833. }
  834. if (!isRecord(parsed)) {
  835. throw new Error(`MCP 配置文件 ${filePath} 必须是 JSON 对象`);
  836. }
  837. return parsed;
  838. }
  839. function isErrnoException(error: unknown): error is NodeJS.ErrnoException {
  840. return error instanceof Error && "code" in error;
  841. }
  842. function formatErrorMessage(error: unknown): string {
  843. return error instanceof Error ? error.message : String(error);
  844. }
  845. async function writeTextAtomic(
  846. filePath: string,
  847. content: string,
  848. ): Promise<void> {
  849. await mkdir(dirname(filePath), { recursive: true });
  850. const tempPath = join(
  851. dirname(filePath),
  852. `${basename(filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
  853. );
  854. try {
  855. // 远端 MCP 配置会持久化 env/header/token 等 secret;
  856. // 临时文件权限不能依赖远端 umask,否则 rename 后 config.json 可能被同组或其他用户读取。
  857. await writeFile(tempPath, content, {
  858. encoding: "utf-8",
  859. mode: SECRET_CONFIG_FILE_MODE,
  860. });
  861. await rename(tempPath, filePath);
  862. } catch (error) {
  863. await rm(tempPath, { force: true });
  864. throw error;
  865. }
  866. }