mcpStore.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /* eslint-disable max-lines -- MCP store 集中维护配置加载、持久化、状态刷新与运行时状态合并,拆分会增加跨状态同步复杂度。 */
  2. /**
  3. * MCP (Model Context Protocol) UI State Store
  4. */
  5. import { create } from "zustand";
  6. import type {
  7. ZCodeAgentMcpServer,
  8. CliMcpSource,
  9. McpConfig,
  10. McpScope,
  11. McpServerConfig,
  12. McpServerStatus,
  13. McpSource,
  14. NativeMcpServerRecord,
  15. ZCodeMcpListMode,
  16. ZCodeMcpServerStatusSnapshot,
  17. ZCodeMcpServer,
  18. } from "@zcode/shared";
  19. import { convertToZCodeAgentMcpServer } from "@zcode/shared";
  20. import { logger } from "@/logger.js";
  21. import {
  22. fetchNativeMcpServers,
  23. migrateLegacyCommonMcpFromDesktop,
  24. persistCliMcpToUserDirectory,
  25. type McpDirectoryService,
  26. type McpPlatformService,
  27. type MigrateLegacyResult,
  28. } from "@/store/mcpStoreDesktop.js";
  29. import {
  30. importLegacyCommonServersToZCodeAgent,
  31. migrateStoredCommonMcpToZCodeAgent,
  32. } from "@/store/mcpStoreMigration.js";
  33. import {
  34. buildServerList,
  35. DEFAULT_MCP_CONFIG,
  36. getServerPriority,
  37. loadPersistedConfig,
  38. makeServerId,
  39. MCP_DELETED_PRELOAD_KEY,
  40. safeReadJson,
  41. safeWriteJson,
  42. } from "@/store/mcpStoreHelpers.js";
  43. import { isRemoteWorkspaceDisconnectedError } from "@/lib/remoteWorkspaceServiceError.js";
  44. import { mergeMcpServerStatusSnapshots } from "@/store/mcpStoreStatusList.js";
  45. let mcpPlatformService: McpPlatformService | null = null;
  46. let mcpDirectoryService: McpDirectoryService | null = null;
  47. export function setMcpStorePlatform(platform: McpPlatformService | null): void {
  48. mcpPlatformService = platform;
  49. }
  50. export function setMcpStoreDirectoryService(service: McpDirectoryService | null): void {
  51. mcpDirectoryService = service;
  52. }
  53. interface UpdateServerStatusOptions {
  54. invalidateStatusListRequests?: boolean;
  55. }
  56. interface McpStoreState {
  57. config: McpConfig;
  58. nativeServers: NativeMcpServerRecord[];
  59. servers: ZCodeMcpServer[];
  60. statusSnapshots: Record<string, ZCodeMcpServerStatusSnapshot>;
  61. currentProjectPath: string;
  62. currentWorkspaceIdentity?: string;
  63. currentAuthorityKey?: string;
  64. enabledStates: Record<string, boolean>;
  65. deletedPreloadMcpServers: Set<string>;
  66. isConfigLoaded: boolean;
  67. currentSessionId: string | null;
  68. loadConfig: () => void;
  69. loadMcpFromUserDirectory: (
  70. directoryService?: McpDirectoryService | null,
  71. workspaceIdentity?: string,
  72. authorityKey?: string,
  73. ) => Promise<boolean>;
  74. ensureLoadedForWorkspace: (
  75. workspacePath?: string,
  76. directoryService?: McpDirectoryService | null,
  77. workspaceIdentity?: string,
  78. authorityKey?: string,
  79. ) => Promise<boolean>;
  80. saveConfig: () => void;
  81. addMcpServer: (name: string, config: McpServerConfig) => void;
  82. updateMcpServer: (name: string, config: McpServerConfig) => void;
  83. deleteMcpServer: (name: string) => void;
  84. addScopedMcpServer: (source: McpSource, name: string, config: McpServerConfig, projectPath?: string) => Promise<void>;
  85. updateScopedMcpServer: (source: McpSource, name: string, config: McpServerConfig, projectPath?: string) => Promise<void>;
  86. deleteScopedMcpServer: (source: McpSource, name: string, projectPath?: string) => void;
  87. addZCodeAgentMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  88. updateZCodeAgentMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  89. deleteZCodeAgentMcpServer: (name: string, projectPath?: string) => void;
  90. addClaudeCliMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  91. updateClaudeCliMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  92. deleteClaudeCliMcpServer: (name: string, projectPath?: string) => void;
  93. addGeminiCliMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  94. updateGeminiCliMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  95. deleteGeminiCliMcpServer: (name: string, projectPath?: string) => void;
  96. addCodexCliMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  97. updateCodexCliMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  98. deleteCodexCliMcpServer: (name: string, projectPath?: string) => void;
  99. addOpenCodeMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  100. updateOpenCodeMcpServer: (name: string, config: McpServerConfig, projectPath?: string) => void;
  101. deleteOpenCodeMcpServer: (name: string, projectPath?: string) => void;
  102. toggleServer: (id: string, enabled: boolean) => Promise<void>;
  103. updateServerStatus: (
  104. id: string,
  105. status: McpServerStatus,
  106. error?: string,
  107. options?: UpdateServerStatusOptions,
  108. ) => void;
  109. beginServerStatusListRefresh: (mode?: ZCodeMcpListMode) => number;
  110. markServerStatusListRefreshFailed: (
  111. error: string,
  112. requestEpoch: number,
  113. mode?: ZCodeMcpListMode,
  114. ) => void;
  115. mergeServerStatusSnapshots: (
  116. statuses: Record<string, ZCodeMcpServerStatusSnapshot>,
  117. requestEpoch: number,
  118. mode?: "connect" | "status",
  119. ) => void;
  120. getServer: (id: string) => ZCodeMcpServer | undefined;
  121. setCurrentProjectPath: (
  122. path: string,
  123. workspaceIdentity?: string,
  124. directoryService?: McpDirectoryService | null,
  125. authorityKey?: string,
  126. ) => void;
  127. getEnabledMcpServersForZCode: (provider: string) => ZCodeAgentMcpServer[];
  128. checkAllServerStatus: (tester: (config: McpServerConfig) => Promise<{ success: boolean; error?: string }>) => Promise<void>;
  129. mergePreloadedMcpServers: (preloaded: Record<string, McpServerConfig>) => void;
  130. deletePreloadedMcpServer: (source: McpSource, name: string) => void;
  131. setCurrentSessionId: (sessionId: string | null) => void;
  132. migrateLegacyCommonMcp: () => Promise<MigrateLegacyResult>;
  133. }
  134. export const useMcpStore = create<McpStoreState>((set, get) => {
  135. let loadMcpPromise: Promise<boolean> | null = null;
  136. let loadMcpWorkspaceKey: string | null = null;
  137. const statusListEpochs: Record<ZCodeMcpListMode, number> = {
  138. connect: 0,
  139. status: 0,
  140. };
  141. function invalidateStatusListRequests(): void {
  142. statusListEpochs.connect += 1;
  143. statusListEpochs.status += 1;
  144. }
  145. function resolveMcpDirectoryService(
  146. directoryService?: McpDirectoryService | null,
  147. workspaceIdentity?: string | null,
  148. ): McpDirectoryService | null {
  149. const effectiveWorkspaceIdentity = workspaceIdentity ?? get().currentWorkspaceIdentity;
  150. if (!effectiveWorkspaceIdentity?.trim()) {
  151. // 本地 workspace 仍要走 desktop platform 路径,才能执行旧 common MCP
  152. // 到用户级 ZCode Agent MCP 的迁移;目录服务只用于远端 workspace 覆盖路由。
  153. return null;
  154. }
  155. return directoryService ?? mcpDirectoryService;
  156. }
  157. function commitState(partial: { config?: McpConfig; nativeServers?: NativeMcpServerRecord[] }): Partial<McpStoreState> {
  158. const state = get();
  159. const nextConfig = partial.config ?? state.config;
  160. const nextNativeServers = partial.nativeServers ?? state.nativeServers;
  161. return {
  162. config: nextConfig,
  163. nativeServers: nextNativeServers,
  164. servers: buildServerList(nextConfig, nextNativeServers, state.enabledStates, state.deletedPreloadMcpServers, state.servers),
  165. };
  166. }
  167. function updateNativeServer(source: CliMcpSource, name: string, config: McpServerConfig, projectPath?: string) {
  168. const nativeServers = get().nativeServers.slice();
  169. const targetIndex = nativeServers.findIndex((server) => server.source === source && server.name === name && server.projectPath === projectPath);
  170. if (targetIndex >= 0) {
  171. const existing = nativeServers[targetIndex];
  172. if (!existing) {
  173. return;
  174. }
  175. nativeServers[targetIndex] = {
  176. ...existing,
  177. config,
  178. };
  179. } else {
  180. // 添加新的服务器记录
  181. const scope: McpScope = projectPath ? "workspace" : "user";
  182. nativeServers.push({
  183. source,
  184. scope,
  185. name,
  186. config,
  187. enabled: true,
  188. projectPath,
  189. });
  190. }
  191. set(commitState({ nativeServers }));
  192. }
  193. async function persistScopedChange(
  194. source: McpSource,
  195. payload: { action: "upsert" | "delete"; source: CliMcpSource; name: string; config?: McpServerConfig; projectPath?: string },
  196. ): Promise<void> {
  197. if (source === "mcp") {
  198. return;
  199. }
  200. await persistCliMcpToUserDirectory(
  201. mcpPlatformService,
  202. payload,
  203. resolveMcpDirectoryService(),
  204. ).catch((error) => {
  205. logger.warn(`[mcpStore] persist ${source} MCP failed`, String(error));
  206. });
  207. }
  208. return {
  209. config: { ...DEFAULT_MCP_CONFIG },
  210. nativeServers: [],
  211. servers: [],
  212. statusSnapshots: {},
  213. currentProjectPath: "",
  214. currentWorkspaceIdentity: undefined,
  215. currentAuthorityKey: undefined,
  216. enabledStates: {},
  217. deletedPreloadMcpServers: new Set(),
  218. isConfigLoaded: false,
  219. currentSessionId: null,
  220. loadConfig: () => {
  221. const config = loadPersistedConfig();
  222. // MCP 启停状态已经迁移到 ~/.zcode/cli/config.json,不能再读取旧 localStorage,
  223. // 否则旧的本地开关会覆盖新的 ZCode Agent 配置来源。
  224. const enabledStates: Record<string, boolean> = {};
  225. const deletedPreload = new Set<string>(safeReadJson<string[]>(MCP_DELETED_PRELOAD_KEY, []));
  226. const servers = buildServerList(config, [], enabledStates, deletedPreload, []);
  227. set({ config, nativeServers: [], enabledStates, deletedPreloadMcpServers: deletedPreload, servers, statusSnapshots: {}, isConfigLoaded: true });
  228. },
  229. loadMcpFromUserDirectory: async (directoryService, workspaceIdentity, authorityKey) => {
  230. if (typeof window === "undefined") {
  231. return false;
  232. }
  233. const requestWorkspacePath = get().currentProjectPath || undefined;
  234. const requestWorkspaceIdentity = workspaceIdentity ?? get().currentWorkspaceIdentity;
  235. const requestAuthorityKey = authorityKey ?? get().currentAuthorityKey;
  236. const requestWorkspaceKey = `${requestAuthorityKey?.trim() || "workspace"}\0${requestWorkspaceIdentity?.trim() || requestWorkspacePath || ""}`;
  237. if (loadMcpPromise && loadMcpWorkspaceKey === requestWorkspaceKey) {
  238. return await loadMcpPromise;
  239. }
  240. if (loadMcpPromise) {
  241. await loadMcpPromise;
  242. }
  243. const latestWorkspacePath = get().currentProjectPath || undefined;
  244. const latestWorkspaceIdentity = get().currentWorkspaceIdentity;
  245. const latestAuthorityKey = get().currentAuthorityKey;
  246. const latestWorkspaceKey = `${latestAuthorityKey?.trim() || "workspace"}\0${latestWorkspaceIdentity?.trim() || latestWorkspacePath || ""}`;
  247. if (latestWorkspaceKey !== requestWorkspaceKey) {
  248. // 该调用等待上一轮 load 时已从 B 切到 C;B 调用持有的 remote
  249. // directoryService 不得继续读取 C,交给 C 自己发起的 ensure/load 调用处理。
  250. return false;
  251. }
  252. // 等待上一 workspace load 期间可能再次切换;目录服务必须按等待后的
  253. // 最新 identity 重新选择,不能拿 B 的 remote service 去读取 C 的路径。
  254. const activeDirectoryService = resolveMcpDirectoryService(
  255. directoryService,
  256. latestWorkspaceIdentity,
  257. );
  258. if (loadMcpPromise && loadMcpWorkspaceKey === latestWorkspaceKey) {
  259. return await loadMcpPromise;
  260. }
  261. loadMcpWorkspaceKey = latestWorkspaceKey;
  262. loadMcpPromise = (async () => {
  263. try {
  264. logger.info(
  265. `[mcpStore] loadMcpFromUserDirectory workspace=${latestWorkspacePath ?? "<none>"} identity=${latestWorkspaceIdentity ?? "<none>"}`,
  266. );
  267. let servers = await fetchNativeMcpServers(
  268. mcpPlatformService,
  269. { workspacePath: latestWorkspacePath },
  270. activeDirectoryService,
  271. );
  272. if (!activeDirectoryService) {
  273. servers = await migrateStoredCommonMcpToZCodeAgent(
  274. mcpPlatformService,
  275. servers,
  276. latestWorkspacePath,
  277. );
  278. }
  279. const currentState = get();
  280. const currentWorkspaceKey = `${currentState.currentAuthorityKey?.trim() || "workspace"}\0${currentState.currentWorkspaceIdentity?.trim() || currentState.currentProjectPath}`;
  281. if (currentWorkspaceKey !== latestWorkspaceKey) {
  282. // workspace A 的异步目录读取可能晚于切换到 B 才返回;
  283. // 旧结果包含 env/header/OAuth secret,不能写回共享 store 后被 B 的 Agent 消费。
  284. return false;
  285. }
  286. set(commitState({ nativeServers: servers }));
  287. return true;
  288. } catch (e) {
  289. // 读取失败不是“配置为空”;调用方必须保持 workspace not-ready,
  290. // 否则会显式下发空 mcpServers 并触发 replace,断开仍在运行的 MCP。
  291. // remote session attachment 绑定前只能拿到断连代理;这是初始化时序,不是
  292. // MCP 配置读取失败。只过滤该精确错误码,避免吞掉真实的目录或 RPC 故障。
  293. if (!isRemoteWorkspaceDisconnectedError(e)) {
  294. logger.warn("[mcpStore] loadMcpFromUserDirectory failed", String(e));
  295. }
  296. return false;
  297. } finally {
  298. loadMcpPromise = null;
  299. loadMcpWorkspaceKey = null;
  300. }
  301. })();
  302. return await loadMcpPromise;
  303. },
  304. ensureLoadedForWorkspace: async (workspacePath, directoryService, workspaceIdentity, authorityKey) => {
  305. if (!get().isConfigLoaded) {
  306. get().loadConfig();
  307. }
  308. const normalizedWorkspacePath = workspacePath ?? "";
  309. const normalizedWorkspaceIdentity = workspaceIdentity?.trim() || undefined;
  310. const normalizedAuthorityKey = authorityKey?.trim() || undefined;
  311. if (
  312. normalizedWorkspacePath !== get().currentProjectPath ||
  313. normalizedWorkspaceIdentity !== get().currentWorkspaceIdentity ||
  314. normalizedAuthorityKey !== get().currentAuthorityKey
  315. ) {
  316. get().setCurrentProjectPath(
  317. normalizedWorkspacePath,
  318. normalizedWorkspaceIdentity,
  319. directoryService,
  320. normalizedAuthorityKey,
  321. );
  322. }
  323. return await get().loadMcpFromUserDirectory(
  324. directoryService,
  325. normalizedWorkspaceIdentity,
  326. normalizedAuthorityKey,
  327. );
  328. },
  329. saveConfig: () => {
  330. const { deletedPreloadMcpServers } = get();
  331. safeWriteJson(MCP_DELETED_PRELOAD_KEY, Array.from(deletedPreloadMcpServers));
  332. },
  333. addMcpServer: (name, config) => get().addZCodeAgentMcpServer(name, config),
  334. updateMcpServer: (name, config) => get().updateZCodeAgentMcpServer(name, config),
  335. deleteMcpServer: (name) => get().deleteZCodeAgentMcpServer(name),
  336. addScopedMcpServer: async (source, name, config, projectPath) => {
  337. invalidateStatusListRequests();
  338. const targetSource: CliMcpSource = source === "mcp" ? "zcodeagentmcp" : source;
  339. // 设置页保存后会马上触发 agent 侧 mcp/list 重连。
  340. // 先等配置落盘,再更新本地 store,避免 agent 读到旧 timeoutMs 后展示旧健康状态。
  341. await persistScopedChange(targetSource, { action: "upsert", source: targetSource, name, config, projectPath });
  342. updateNativeServer(targetSource, name, config, projectPath);
  343. },
  344. updateScopedMcpServer: async (source, name, config, projectPath) => {
  345. invalidateStatusListRequests();
  346. const targetSource: CliMcpSource = source === "mcp" ? "zcodeagentmcp" : source;
  347. // 修复原因同新增:本地状态变化会驱动健康状态刷新,必须在磁盘配置更新后发生。
  348. await persistScopedChange(targetSource, { action: "upsert", source: targetSource, name, config, projectPath });
  349. updateNativeServer(targetSource, name, config, projectPath);
  350. },
  351. deleteScopedMcpServer: (source, name, projectPath) => {
  352. invalidateStatusListRequests();
  353. const targetSource: CliMcpSource = source === "mcp" ? "zcodeagentmcp" : source;
  354. persistScopedChange(targetSource, { action: "delete", source: targetSource, name, projectPath });
  355. set(commitState({
  356. nativeServers: get().nativeServers.filter((server) => !(server.source === targetSource && server.name === name && server.projectPath === projectPath)),
  357. }));
  358. },
  359. addClaudeCliMcpServer: (name, config, projectPath) => get().addScopedMcpServer("claudeclimcp", name, config, projectPath),
  360. updateClaudeCliMcpServer: (name, config, projectPath) => get().updateScopedMcpServer("claudeclimcp", name, config, projectPath),
  361. deleteClaudeCliMcpServer: (name, projectPath) => get().deleteScopedMcpServer("claudeclimcp", name, projectPath),
  362. addGeminiCliMcpServer: (name, config, projectPath) => get().addScopedMcpServer("geminiclimcp", name, config, projectPath),
  363. updateGeminiCliMcpServer: (name, config, projectPath) => get().updateScopedMcpServer("geminiclimcp", name, config, projectPath),
  364. deleteGeminiCliMcpServer: (name, projectPath) => get().deleteScopedMcpServer("geminiclimcp", name, projectPath),
  365. addCodexCliMcpServer: (name, config, projectPath) => get().addScopedMcpServer("codexclimcp", name, config, projectPath),
  366. updateCodexCliMcpServer: (name, config, projectPath) => get().updateScopedMcpServer("codexclimcp", name, config, projectPath),
  367. deleteCodexCliMcpServer: (name, projectPath) => get().deleteScopedMcpServer("codexclimcp", name, projectPath),
  368. addOpenCodeMcpServer: (name, config, projectPath) => get().addScopedMcpServer("opencodemcp", name, config, projectPath),
  369. updateOpenCodeMcpServer: (name, config, projectPath) => get().updateScopedMcpServer("opencodemcp", name, config, projectPath),
  370. deleteOpenCodeMcpServer: (name, projectPath) => get().deleteScopedMcpServer("opencodemcp", name, projectPath),
  371. addZCodeAgentMcpServer: (name, config, projectPath) => get().addScopedMcpServer("zcodeagentmcp", name, config, projectPath),
  372. updateZCodeAgentMcpServer: (name, config, projectPath) => get().updateScopedMcpServer("zcodeagentmcp", name, config, projectPath),
  373. deleteZCodeAgentMcpServer: (name, projectPath) => get().deleteScopedMcpServer("zcodeagentmcp", name, projectPath),
  374. toggleServer: async (id, enabled) => {
  375. invalidateStatusListRequests();
  376. const targetServer = get().servers.find((server) => server.id === id);
  377. if (targetServer && targetServer.source !== "mcp") {
  378. // 开关变化会触发 agent 侧 mcp/list 读取磁盘配置做真实连接。
  379. // 必须先等 enable 状态落盘,再更新本地列表驱动刷新,否则 agent 会读到旧开关。
  380. await persistCliMcpToUserDirectory(mcpPlatformService, {
  381. action: "set-enabled",
  382. source: targetServer.source,
  383. name: targetServer.name,
  384. enabled,
  385. projectPath: targetServer.projectPath,
  386. location: targetServer.location,
  387. }, resolveMcpDirectoryService()).catch((error) => {
  388. logger.warn("[mcpStore] persist MCP enabled override failed", String(error));
  389. });
  390. }
  391. set((state) => {
  392. const nextEnabledStates = { ...state.enabledStates, [id]: enabled };
  393. return {
  394. enabledStates: nextEnabledStates,
  395. servers: state.servers.map((s) => (s.id === id ? { ...s, enabled } : s)),
  396. };
  397. });
  398. },
  399. updateServerStatus: (id, status, error, options) => {
  400. if (options?.invalidateStatusListRequests !== false) {
  401. invalidateStatusListRequests();
  402. }
  403. set((state) => ({
  404. servers: state.servers.map((s) =>
  405. s.id === id
  406. ? {
  407. ...s,
  408. status,
  409. authorization: undefined,
  410. error,
  411. failureKind: status === "error" ? "connection_failed" : undefined,
  412. serverRequestId: undefined,
  413. toolCount: status === "connected" ? s.toolCount : undefined,
  414. changed: status === "error" ? s.changed : false,
  415. lastConnected: status === "connected" ? new Date() : s.lastConnected,
  416. }
  417. : s,
  418. ),
  419. }));
  420. },
  421. beginServerStatusListRefresh: (mode = "connect") => {
  422. statusListEpochs[mode] += 1;
  423. const requestEpoch = statusListEpochs[mode];
  424. if (mode === "status") {
  425. // OAuth 1s status-only 轮询只读取 runtime snapshot;不能反复清空
  426. // authorization/toolCount 或把用户同时编辑的其他 MCP 投影成 connecting。
  427. return requestEpoch;
  428. }
  429. // agent 侧 mcp/list 会等待所有 MCP 连接完成才返回;如果插件 MCP 还在 30s 超时中,
  430. // 修改 timeoutMs 后本地列表会长时间停在 unknown,看起来像没有立即重新检查。
  431. set((state) => ({
  432. servers: state.servers.map((server) => {
  433. const enabled = state.enabledStates[server.id] ?? server.enabled;
  434. if (
  435. server.source !== "zcodeagentmcp" ||
  436. !enabled ||
  437. (!server.changed && server.status !== "unknown")
  438. ) {
  439. return server;
  440. }
  441. return {
  442. ...server,
  443. status: "connecting",
  444. authorization: undefined,
  445. error: undefined,
  446. failureKind: undefined,
  447. serverRequestId: undefined,
  448. toolCount: undefined,
  449. };
  450. }),
  451. }));
  452. return requestEpoch;
  453. },
  454. markServerStatusListRefreshFailed: (error, requestEpoch, mode = "connect") => {
  455. if (requestEpoch !== statusListEpochs[mode] || mode === "status") {
  456. // OAuth 轮询是只读的 best-effort status 请求;临时失败不能清空已有
  457. // authorization snapshot,也不能把同一列表中仍在连接的 MCP 批量标红。
  458. return;
  459. }
  460. set((state) => ({
  461. statusSnapshots: {},
  462. servers: state.servers.map((server) => {
  463. const enabled = state.enabledStates[server.id] ?? server.enabled;
  464. if (
  465. server.source !== "zcodeagentmcp" ||
  466. !enabled ||
  467. server.status !== "connecting"
  468. ) {
  469. return server;
  470. }
  471. return {
  472. ...server,
  473. status: "error",
  474. authorization: undefined,
  475. error,
  476. failureKind: "status_unavailable",
  477. serverRequestId: undefined,
  478. toolCount: undefined,
  479. };
  480. }),
  481. }));
  482. },
  483. mergeServerStatusSnapshots: (statuses, requestEpoch, mode = "connect") => {
  484. if (requestEpoch !== statusListEpochs[mode]) {
  485. return;
  486. }
  487. set((state) => {
  488. const nextStatusSnapshots =
  489. mode === "status"
  490. ? { ...state.statusSnapshots, ...statuses }
  491. : statuses;
  492. return {
  493. statusSnapshots: nextStatusSnapshots,
  494. servers: mergeMcpServerStatusSnapshots(
  495. state.servers,
  496. nextStatusSnapshots,
  497. {
  498. // Bugfix:OAuth 轮询的 status-only 响应可能只包含 pending 子集。
  499. // 缺失项不能按全量 mcp/list 处理,否则会把其他 MCP 误标为 agent 未返回。
  500. markMissingConnectingAsError: mode !== "status",
  501. },
  502. ),
  503. };
  504. });
  505. },
  506. getServer: (id) => get().servers.find((s) => s.id === id),
  507. setCurrentProjectPath: (path, workspaceIdentity, directoryService, authorityKey) => {
  508. invalidateStatusListRequests();
  509. const {
  510. config,
  511. currentProjectPath,
  512. currentWorkspaceIdentity,
  513. currentAuthorityKey,
  514. deletedPreloadMcpServers,
  515. enabledStates,
  516. isConfigLoaded,
  517. nativeServers,
  518. servers,
  519. } = get();
  520. const normalizedWorkspaceIdentity = workspaceIdentity?.trim() || undefined;
  521. const normalizedAuthorityKey = authorityKey?.trim() || undefined;
  522. const workspaceChanged =
  523. path !== currentProjectPath ||
  524. normalizedWorkspaceIdentity !== currentWorkspaceIdentity ||
  525. normalizedAuthorityKey !== currentAuthorityKey;
  526. const nextNativeServers = workspaceChanged ? [] : nativeServers;
  527. set({
  528. currentProjectPath: path,
  529. currentWorkspaceIdentity: normalizedWorkspaceIdentity,
  530. currentAuthorityKey: normalizedAuthorityKey,
  531. nativeServers: nextNativeServers,
  532. statusSnapshots: {},
  533. servers: buildServerList(
  534. config,
  535. nextNativeServers,
  536. enabledStates,
  537. deletedPreloadMcpServers,
  538. workspaceChanged ? [] : servers,
  539. ),
  540. });
  541. if (isConfigLoaded && workspaceChanged) {
  542. // 切换到远程 workspace 后配置加载是异步的;等待期间必须先清空 A 的
  543. // user-level MCP,不能把其 env/header/OAuth clientSecret 暂存为 B 的可发送配置。
  544. void get().loadMcpFromUserDirectory(directoryService, normalizedWorkspaceIdentity, normalizedAuthorityKey);
  545. }
  546. },
  547. getEnabledMcpServersForZCode: (_provider) => {
  548. const { servers, enabledStates, currentProjectPath } = get();
  549. const candidates = new Map<string, ZCodeMcpServer>();
  550. for (const server of servers) {
  551. const isEnabled = enabledStates[server.id] ?? server.enabled;
  552. if (!isEnabled) continue;
  553. if (server.source !== "zcodeagentmcp") continue;
  554. if (server.scope === "workspace" && server.projectPath !== currentProjectPath) continue;
  555. const existing = candidates.get(server.name);
  556. if (!existing || getServerPriority(server) > getServerPriority(existing)) {
  557. candidates.set(server.name, server);
  558. }
  559. }
  560. const result: ZCodeAgentMcpServer[] = [];
  561. for (const server of candidates.values()) {
  562. const zcodeAgentServer = convertToZCodeAgentMcpServer(server.name, server.config);
  563. if (zcodeAgentServer) result.push(zcodeAgentServer);
  564. }
  565. return result;
  566. },
  567. checkAllServerStatus: async (tester) => {
  568. for (const server of get().servers) {
  569. const isEnabled = get().enabledStates[server.id] ?? server.enabled;
  570. if (!isEnabled || (!server.changed && server.status !== "unknown")) continue;
  571. get().updateServerStatus(server.id, "connecting");
  572. try {
  573. const result = await tester(server.config);
  574. get().updateServerStatus(server.id, result.success ? "connected" : "error", result.success ? undefined : (result.error ?? "Connection failed"));
  575. } catch (e) {
  576. get().updateServerStatus(server.id, "error", String(e));
  577. }
  578. }
  579. },
  580. mergePreloadedMcpServers: (preloaded) => {
  581. const { deletedPreloadMcpServers, nativeServers } = get();
  582. const targetSource: CliMcpSource = "zcodeagentmcp";
  583. const nextNativeServers = nativeServers.slice();
  584. let changed = false;
  585. for (const [name, cfg] of Object.entries(preloaded)) {
  586. const serverId = makeServerId(targetSource, name);
  587. const exists = nextNativeServers.some((server) => server.source === targetSource && server.name === name && !server.projectPath);
  588. if (deletedPreloadMcpServers.has(serverId) || exists) continue;
  589. nextNativeServers.push({
  590. source: targetSource,
  591. scope: "user",
  592. name,
  593. config: cfg,
  594. enabled: true,
  595. });
  596. persistScopedChange(targetSource, { action: "upsert", source: targetSource, name, config: cfg });
  597. changed = true;
  598. }
  599. if (!changed) return;
  600. set(commitState({ nativeServers: nextNativeServers }));
  601. },
  602. deletePreloadedMcpServer: (source, name) => {
  603. const targetSource: CliMcpSource = source === "mcp" ? "zcodeagentmcp" : source;
  604. const key = makeServerId(targetSource, name);
  605. persistScopedChange(targetSource, { action: "delete", source: targetSource, name });
  606. set((state) => {
  607. const nextDeleted = new Set(state.deletedPreloadMcpServers);
  608. nextDeleted.add(key);
  609. safeWriteJson(MCP_DELETED_PRELOAD_KEY, Array.from(nextDeleted));
  610. const nextNativeServers = state.nativeServers.filter((server) => !(server.source === targetSource && server.name === name && !server.projectPath));
  611. return {
  612. deletedPreloadMcpServers: nextDeleted,
  613. nativeServers: nextNativeServers,
  614. servers: buildServerList(state.config, nextNativeServers, state.enabledStates, nextDeleted, state.servers),
  615. };
  616. });
  617. },
  618. setCurrentSessionId: (sessionId) => set({ currentSessionId: sessionId }),
  619. migrateLegacyCommonMcp: async () => {
  620. const result = await migrateLegacyCommonMcpFromDesktop(mcpPlatformService);
  621. const latestWorkspacePath = get().currentProjectPath || undefined;
  622. const currentNativeServers = get().nativeServers.length > 0
  623. ? get().nativeServers
  624. : await fetchNativeMcpServers(mcpPlatformService, { workspacePath: latestWorkspacePath });
  625. const migration = await importLegacyCommonServersToZCodeAgent(mcpPlatformService, result.servers ?? {}, currentNativeServers, result.sourcePath);
  626. if (migration.changed) {
  627. const servers = await fetchNativeMcpServers(mcpPlatformService, { workspacePath: latestWorkspacePath });
  628. set(commitState({ nativeServers: servers }));
  629. }
  630. return migration;
  631. },
  632. };
  633. });