mcpStore.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. setMcpStoreDirectoryService,
  4. setMcpStorePlatform,
  5. useMcpStore,
  6. } from "@/store/mcpStore.js";
  7. import { DEFAULT_MCP_CONFIG, MCP_CONFIG_KEY } from "@/store/mcpStoreHelpers.js";
  8. import { logger } from "@/logger.js";
  9. function createLocalStorageStub(initial: Record<string, string> = {}) {
  10. const values = new Map(Object.entries(initial));
  11. return {
  12. getItem: vi.fn((key: string) => values.get(key) ?? null),
  13. setItem: vi.fn((key: string, value: string) => {
  14. values.set(key, value);
  15. }),
  16. removeItem: vi.fn((key: string) => {
  17. values.delete(key);
  18. }),
  19. };
  20. }
  21. describe("mcpStore", () => {
  22. beforeEach(() => {
  23. vi.unstubAllGlobals();
  24. setMcpStoreDirectoryService(null);
  25. setMcpStorePlatform(null);
  26. useMcpStore.setState((state) => ({
  27. ...state,
  28. config: { ...DEFAULT_MCP_CONFIG },
  29. nativeServers: [],
  30. servers: [],
  31. statusSnapshots: {},
  32. currentProjectPath: "",
  33. currentWorkspaceIdentity: undefined,
  34. enabledStates: {},
  35. deletedPreloadMcpServers: new Set(),
  36. isConfigLoaded: false,
  37. currentSessionId: null,
  38. }));
  39. });
  40. it("无 window 环境时,ensureLoadedForWorkspace 也不会抛错", async () => {
  41. const globalLike = globalThis as Record<string, unknown>;
  42. delete globalLike.window;
  43. await expect(
  44. useMcpStore.getState().ensureLoadedForWorkspace("/tmp/mcp-workspace"),
  45. ).resolves.toBe(false);
  46. });
  47. it("目录配置读取失败时保持现有 MCP,并返回未加载", async () => {
  48. vi.stubGlobal("window", {});
  49. const existingServer = {
  50. id: "zcodeagentmcp-global-everything",
  51. name: "everything",
  52. config: { type: "stdio" as const, command: "node", args: ["server.mjs"] },
  53. enabled: true,
  54. status: "connected" as const,
  55. source: "zcodeagentmcp" as const,
  56. scope: "user" as const,
  57. toolCount: 1,
  58. };
  59. setMcpStorePlatform({
  60. loadMcpFromUserDirectory: vi.fn(async () => {
  61. throw new SyntaxError("invalid MCP config");
  62. }),
  63. migrateLegacyCommonMcp: vi.fn(async () => ({
  64. importedCount: 0,
  65. servers: {},
  66. skippedCount: 0,
  67. totalCount: 0,
  68. })),
  69. saveMcpToUserDirectory: vi.fn(async () => ({ success: true })),
  70. });
  71. useMcpStore.setState({
  72. currentProjectPath: "/local/workspace",
  73. isConfigLoaded: true,
  74. servers: [existingServer],
  75. });
  76. await expect(
  77. useMcpStore.getState().ensureLoadedForWorkspace("/local/workspace"),
  78. ).resolves.toBe(false);
  79. expect(useMcpStore.getState().servers).toEqual([existingServer]);
  80. });
  81. it("传入目录服务时按当前 workspace 服务加载 MCP", async () => {
  82. vi.stubGlobal("window", {});
  83. const platformLoad = vi.fn(async () => ({
  84. servers: [
  85. {
  86. source: "zcodeagentmcp" as const,
  87. scope: "user" as const,
  88. name: "local-http",
  89. config: { type: "http" as const, url: "https://local.example.test/mcp" },
  90. },
  91. ],
  92. }));
  93. setMcpStorePlatform({
  94. loadMcpFromUserDirectory: platformLoad,
  95. migrateLegacyCommonMcp: vi.fn(async () => ({
  96. importedCount: 0,
  97. servers: {},
  98. skippedCount: 0,
  99. totalCount: 0,
  100. })),
  101. saveMcpToUserDirectory: vi.fn(async () => ({ success: true })),
  102. });
  103. const directoryService = {
  104. loadMcpFromUserDirectory: vi.fn(async () => ({
  105. servers: [
  106. {
  107. source: "zcodeagentmcp" as const,
  108. scope: "user" as const,
  109. name: "remote-http",
  110. config: { type: "http" as const, url: "https://remote.example.test/mcp" },
  111. },
  112. ],
  113. })),
  114. saveMcpToUserDirectory: vi.fn(async () => {}),
  115. };
  116. await useMcpStore
  117. .getState()
  118. .ensureLoadedForWorkspace("/remote/workspace", directoryService, "ssh:host:/remote/workspace");
  119. expect(directoryService.loadMcpFromUserDirectory).toHaveBeenCalledWith({
  120. workspacePath: "/remote/workspace",
  121. });
  122. expect(platformLoad).not.toHaveBeenCalled();
  123. expect(useMcpStore.getState().servers.map((server) => server.name)).toEqual([
  124. "remote-http",
  125. ]);
  126. });
  127. it("切换到远程 workspace 时立即清空本地配置并丢弃晚到的旧加载结果", async () => {
  128. vi.stubGlobal("window", {});
  129. let resolveLocalLoad!: (value: {
  130. servers: Array<{
  131. config: {
  132. command: string;
  133. env: Record<string, string>;
  134. type: "stdio";
  135. };
  136. name: string;
  137. scope: "user";
  138. source: "zcodeagentmcp";
  139. }>;
  140. }) => void;
  141. const platformLoad = vi.fn(
  142. () =>
  143. new Promise<{
  144. servers: Array<{
  145. config: {
  146. command: string;
  147. env: Record<string, string>;
  148. type: "stdio";
  149. };
  150. name: string;
  151. scope: "user";
  152. source: "zcodeagentmcp";
  153. }>;
  154. }>((resolve) => {
  155. resolveLocalLoad = resolve;
  156. }),
  157. );
  158. setMcpStorePlatform({
  159. loadMcpFromUserDirectory: platformLoad,
  160. migrateLegacyCommonMcp: vi.fn(async () => ({
  161. importedCount: 0,
  162. servers: {},
  163. skippedCount: 0,
  164. totalCount: 0,
  165. })),
  166. saveMcpToUserDirectory: vi.fn(async () => ({ success: true })),
  167. });
  168. const directoryService = {
  169. loadMcpFromUserDirectory: vi.fn(async () => ({
  170. servers: [
  171. {
  172. source: "zcodeagentmcp" as const,
  173. scope: "user" as const,
  174. name: "remote-b",
  175. config: {
  176. type: "http" as const,
  177. url: "https://workspace-b.example.test/mcp",
  178. headers: { "X-Workspace": "workspace-b" },
  179. },
  180. },
  181. ],
  182. })),
  183. saveMcpToUserDirectory: vi.fn(async () => {}),
  184. };
  185. const loadWorkspaceA = useMcpStore
  186. .getState()
  187. .ensureLoadedForWorkspace("/local/workspace-a");
  188. expect(platformLoad).toHaveBeenCalledTimes(1);
  189. const loadWorkspaceB = useMcpStore
  190. .getState()
  191. .ensureLoadedForWorkspace(
  192. "/remote/workspace-b",
  193. directoryService,
  194. "ssh://dev/remote/workspace-b",
  195. );
  196. expect(useMcpStore.getState().servers).toEqual([]);
  197. resolveLocalLoad({
  198. servers: [
  199. {
  200. source: "zcodeagentmcp",
  201. scope: "user",
  202. name: "local-a-secret",
  203. config: {
  204. type: "stdio",
  205. command: "local-secret-server",
  206. env: { API_KEY: "workspace-a-env-secret" },
  207. },
  208. },
  209. ],
  210. });
  211. await Promise.all([loadWorkspaceA, loadWorkspaceB]);
  212. expect(directoryService.loadMcpFromUserDirectory).toHaveBeenCalledWith({
  213. workspacePath: "/remote/workspace-b",
  214. });
  215. expect(useMcpStore.getState().servers.map((server) => server.name)).toEqual([
  216. "remote-b",
  217. ]);
  218. expect(JSON.stringify(useMcpStore.getState().servers)).not.toContain("workspace-a-");
  219. });
  220. it("远端 workspace attachment 绑定前不把预期断连记录成 MCP 警告", async () => {
  221. vi.stubGlobal("window", {});
  222. const disconnectedError = Object.assign(
  223. new Error("ZCODE_REMOTE_WORKSPACE_DISCONNECTED"),
  224. { code: "ZCODE_REMOTE_WORKSPACE_DISCONNECTED" },
  225. );
  226. const directoryService = {
  227. loadMcpFromUserDirectory: vi.fn(async () => {
  228. throw disconnectedError;
  229. }),
  230. saveMcpToUserDirectory: vi.fn(async () => {}),
  231. };
  232. const warn = vi.spyOn(logger, "warn").mockImplementation(() => undefined);
  233. await useMcpStore
  234. .getState()
  235. .ensureLoadedForWorkspace(
  236. "/remote/workspace",
  237. directoryService,
  238. "remote:ssh:host:/remote/workspace",
  239. );
  240. expect(warn).not.toHaveBeenCalled();
  241. warn.mockRestore();
  242. });
  243. it("MCP 真实目录读取失败仍保留警告", async () => {
  244. vi.stubGlobal("window", {});
  245. const directoryService = {
  246. loadMcpFromUserDirectory: vi.fn(async () => {
  247. throw new Error("EACCES: permission denied");
  248. }),
  249. saveMcpToUserDirectory: vi.fn(async () => {}),
  250. };
  251. const warn = vi.spyOn(logger, "warn").mockImplementation(() => undefined);
  252. await useMcpStore
  253. .getState()
  254. .ensureLoadedForWorkspace(
  255. "/remote/workspace",
  256. directoryService,
  257. "remote:ssh:host:/remote/workspace",
  258. );
  259. expect(warn).toHaveBeenCalledWith(
  260. "[mcpStore] loadMcpFromUserDirectory failed",
  261. "Error: EACCES: permission denied",
  262. );
  263. warn.mockRestore();
  264. });
  265. it("本地 workspace 即使存在目录服务也保留 platform 迁移 legacy common MCP", async () => {
  266. vi.stubGlobal("window", {});
  267. vi.stubGlobal(
  268. "localStorage",
  269. createLocalStorageStub({
  270. [MCP_CONFIG_KEY]: JSON.stringify({
  271. mcp: {
  272. mcpServers: {
  273. legacyHttp: {
  274. type: "http",
  275. url: "https://legacy.example.test/mcp",
  276. },
  277. },
  278. },
  279. }),
  280. }),
  281. );
  282. const platformLoad = vi
  283. .fn()
  284. .mockResolvedValueOnce({ servers: [] })
  285. .mockResolvedValueOnce({
  286. servers: [
  287. {
  288. source: "zcodeagentmcp" as const,
  289. scope: "user" as const,
  290. name: "legacyHttp",
  291. config: {
  292. type: "http" as const,
  293. url: "https://legacy.example.test/mcp",
  294. },
  295. },
  296. ],
  297. });
  298. const platformSave = vi.fn(async () => ({ success: true }));
  299. setMcpStorePlatform({
  300. loadMcpFromUserDirectory: platformLoad,
  301. migrateLegacyCommonMcp: vi.fn(async () => ({
  302. importedCount: 0,
  303. servers: {},
  304. skippedCount: 0,
  305. totalCount: 0,
  306. })),
  307. saveMcpToUserDirectory: platformSave,
  308. });
  309. const directoryService = {
  310. loadMcpFromUserDirectory: vi.fn(async () => ({
  311. servers: [
  312. {
  313. source: "zcodeagentmcp" as const,
  314. scope: "user" as const,
  315. name: "remote-http",
  316. config: { type: "http" as const, url: "https://remote.example.test/mcp" },
  317. },
  318. ],
  319. })),
  320. saveMcpToUserDirectory: vi.fn(async () => {}),
  321. };
  322. setMcpStoreDirectoryService(directoryService);
  323. await useMcpStore
  324. .getState()
  325. .ensureLoadedForWorkspace("/local/workspace", directoryService);
  326. expect(directoryService.loadMcpFromUserDirectory).not.toHaveBeenCalled();
  327. expect(platformLoad).toHaveBeenCalledWith({ workspacePath: "/local/workspace" });
  328. expect(platformSave).toHaveBeenCalledWith({
  329. action: "upsert",
  330. source: "zcodeagentmcp",
  331. name: "legacyHttp",
  332. config: {
  333. type: "http",
  334. url: "https://legacy.example.test/mcp",
  335. },
  336. });
  337. expect(useMcpStore.getState().servers.map((server) => server.name)).toEqual([
  338. "legacyHttp",
  339. ]);
  340. });
  341. it("批量合并只更新 ZCode Agent MCP 行且清理 changed", () => {
  342. useMcpStore.setState({
  343. servers: [
  344. {
  345. id: "zcodeagentmcp-global-filesystem",
  346. name: "filesystem",
  347. config: { type: "stdio", command: "node", args: ["server.js"] },
  348. enabled: true,
  349. changed: true,
  350. status: "unknown",
  351. source: "zcodeagentmcp",
  352. scope: "user",
  353. },
  354. {
  355. id: "claudeclimcp-global-filesystem",
  356. name: "filesystem",
  357. config: { type: "stdio", command: "node", args: ["server.js"] },
  358. enabled: true,
  359. changed: true,
  360. status: "unknown",
  361. source: "claudeclimcp",
  362. scope: "user",
  363. },
  364. ],
  365. });
  366. const epoch = useMcpStore.getState().beginServerStatusListRefresh();
  367. useMcpStore.getState().mergeServerStatusSnapshots(
  368. {
  369. filesystem: {
  370. status: "connected",
  371. transport: "stdio",
  372. toolCount: 2,
  373. updatedAt: "2026-06-23T00:00:00.000Z",
  374. },
  375. },
  376. epoch,
  377. );
  378. const [zcodeServer, claudeServer] = useMcpStore.getState().servers;
  379. expect(zcodeServer).toMatchObject({
  380. status: "connected",
  381. toolCount: 2,
  382. changed: false,
  383. });
  384. expect(claudeServer).toMatchObject({
  385. status: "unknown",
  386. changed: true,
  387. });
  388. });
  389. it("批量状态结果会保留待授权 OAuth URL", () => {
  390. useMcpStore.setState({
  391. servers: [
  392. {
  393. id: "zcodeagentmcp-global-notion",
  394. name: "notion",
  395. config: {
  396. type: "http",
  397. url: "https://mcp.notion.example.test/mcp",
  398. oauth: { type: "authorization_code" },
  399. },
  400. enabled: true,
  401. changed: true,
  402. status: "unknown",
  403. source: "zcodeagentmcp",
  404. scope: "user",
  405. },
  406. ],
  407. });
  408. const epoch = useMcpStore.getState().beginServerStatusListRefresh();
  409. useMcpStore.getState().mergeServerStatusSnapshots(
  410. {
  411. notion: {
  412. authorization: {
  413. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  414. startedAt: "2026-06-23T00:00:00.000Z",
  415. type: "oauth_authorization_code",
  416. },
  417. status: "connecting",
  418. transport: "http",
  419. toolCount: 0,
  420. updatedAt: "2026-06-23T00:00:00.000Z",
  421. },
  422. },
  423. epoch,
  424. );
  425. expect(useMcpStore.getState().servers[0]).toMatchObject({
  426. authorization: {
  427. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  428. type: "oauth_authorization_code",
  429. },
  430. status: "connecting",
  431. });
  432. });
  433. it("status-only 状态结果会 patch merge 并保留其他 MCP snapshot", () => {
  434. useMcpStore.setState({
  435. servers: [
  436. {
  437. id: "zcodeagentmcp-global-everything",
  438. name: "everything",
  439. config: { type: "stdio", command: "npx", args: ["everything"] },
  440. enabled: true,
  441. changed: false,
  442. status: "connected",
  443. source: "zcodeagentmcp",
  444. scope: "user",
  445. toolCount: 9,
  446. },
  447. {
  448. id: "zcodeagentmcp-global-plugin-canva",
  449. name: "plugin:canva:canva",
  450. config: { type: "http", url: "https://mcp.canva.example.test/mcp" },
  451. enabled: true,
  452. changed: false,
  453. status: "connecting",
  454. source: "zcodeagentmcp",
  455. scope: "user",
  456. authorization: {
  457. authorizationUrl: "https://auth.canva.example.test/authorize",
  458. startedAt: "2026-07-09T00:00:00.000Z",
  459. type: "oauth_authorization_code",
  460. },
  461. },
  462. ],
  463. statusSnapshots: {
  464. everything: {
  465. status: "connected",
  466. transport: "stdio",
  467. toolCount: 9,
  468. updatedAt: "2026-07-09T00:00:00.000Z",
  469. },
  470. "plugin:canva:canva": {
  471. authorization: {
  472. authorizationUrl: "https://auth.canva.example.test/authorize",
  473. startedAt: "2026-07-09T00:00:00.000Z",
  474. type: "oauth_authorization_code",
  475. },
  476. status: "connecting",
  477. transport: "http",
  478. toolCount: 0,
  479. updatedAt: "2026-07-09T00:00:00.000Z",
  480. },
  481. },
  482. });
  483. const epoch = useMcpStore.getState().beginServerStatusListRefresh("status");
  484. useMcpStore.getState().mergeServerStatusSnapshots(
  485. {
  486. "plugin:canva:canva": {
  487. status: "connected",
  488. transport: "http",
  489. toolCount: 33,
  490. updatedAt: "2026-07-09T00:00:01.000Z",
  491. },
  492. },
  493. epoch,
  494. "status",
  495. );
  496. expect(useMcpStore.getState().statusSnapshots).toMatchObject({
  497. everything: {
  498. status: "connected",
  499. toolCount: 9,
  500. },
  501. "plugin:canva:canva": {
  502. status: "connected",
  503. toolCount: 33,
  504. },
  505. });
  506. expect(useMcpStore.getState().servers).toEqual([
  507. expect.objectContaining({
  508. name: "everything",
  509. status: "connected",
  510. toolCount: 9,
  511. }),
  512. expect.objectContaining({
  513. authorization: undefined,
  514. name: "plugin:canva:canva",
  515. status: "connected",
  516. toolCount: 33,
  517. }),
  518. ]);
  519. });
  520. it("connect 状态结果仍按全量 replace 处理缺失的连接中 server", () => {
  521. useMcpStore.setState({
  522. servers: [
  523. {
  524. id: "zcodeagentmcp-global-canva",
  525. name: "canva",
  526. config: { type: "http", url: "https://mcp.canva.example.test/mcp" },
  527. enabled: true,
  528. changed: true,
  529. status: "unknown",
  530. source: "zcodeagentmcp",
  531. scope: "user",
  532. },
  533. ],
  534. statusSnapshots: {
  535. canva: {
  536. status: "connected",
  537. transport: "http",
  538. toolCount: 33,
  539. updatedAt: "2026-07-09T00:00:00.000Z",
  540. },
  541. },
  542. });
  543. const epoch = useMcpStore.getState().beginServerStatusListRefresh();
  544. useMcpStore.getState().mergeServerStatusSnapshots({}, epoch, "connect");
  545. expect(useMcpStore.getState().statusSnapshots).toEqual({});
  546. expect(useMcpStore.getState().servers[0]).toMatchObject({
  547. status: "error",
  548. error: undefined,
  549. failureKind: "status_unavailable",
  550. toolCount: undefined,
  551. });
  552. });
  553. it("迟到的批量状态不会覆盖手动检查结果", () => {
  554. useMcpStore.setState({
  555. servers: [
  556. {
  557. id: "zcodeagentmcp-global-filesystem",
  558. name: "filesystem",
  559. config: { type: "stdio", command: "node", args: ["server.js"] },
  560. enabled: true,
  561. changed: true,
  562. status: "unknown",
  563. source: "zcodeagentmcp",
  564. scope: "user",
  565. },
  566. ],
  567. });
  568. const epoch = useMcpStore.getState().beginServerStatusListRefresh();
  569. useMcpStore.getState().updateServerStatus("zcodeagentmcp-global-filesystem", "error", "manual");
  570. useMcpStore.getState().mergeServerStatusSnapshots(
  571. {
  572. filesystem: {
  573. status: "connected",
  574. transport: "stdio",
  575. toolCount: 2,
  576. updatedAt: "2026-06-23T00:00:00.000Z",
  577. },
  578. },
  579. epoch,
  580. );
  581. expect(useMcpStore.getState().servers[0]).toMatchObject({
  582. status: "error",
  583. error: "manual",
  584. });
  585. });
  586. it("临时展示态更新不会作废当前批量状态结果", () => {
  587. useMcpStore.setState({
  588. servers: [
  589. {
  590. id: "zcodeagentmcp-global-filesystem",
  591. name: "filesystem",
  592. config: { type: "stdio", command: "node", args: ["server.js"] },
  593. enabled: true,
  594. changed: true,
  595. status: "unknown",
  596. source: "zcodeagentmcp",
  597. scope: "user",
  598. },
  599. ],
  600. });
  601. const epoch = useMcpStore.getState().beginServerStatusListRefresh();
  602. useMcpStore.getState().updateServerStatus(
  603. "zcodeagentmcp-global-filesystem",
  604. "connecting",
  605. undefined,
  606. { invalidateStatusListRequests: false },
  607. );
  608. useMcpStore.getState().mergeServerStatusSnapshots(
  609. {
  610. filesystem: {
  611. status: "failed",
  612. transport: "stdio",
  613. error: "spawn missing ENOENT",
  614. updatedAt: "2026-06-23T00:00:00.000Z",
  615. },
  616. },
  617. epoch,
  618. );
  619. expect(useMcpStore.getState().servers[0]).toMatchObject({
  620. status: "error",
  621. error: "spawn missing ENOENT",
  622. });
  623. });
  624. it("批量状态刷新开始时会立即标记待检查的 ZCode Agent MCP 为连接中", () => {
  625. useMcpStore.setState({
  626. servers: [
  627. {
  628. id: "zcodeagentmcp-global-context7",
  629. name: "context7",
  630. config: { type: "stdio", command: "npx", args: ["-y", "@upstash/context7-mcp"], timeoutMs: 3 },
  631. enabled: true,
  632. changed: true,
  633. status: "unknown",
  634. error: "old error",
  635. toolCount: 2,
  636. source: "zcodeagentmcp",
  637. scope: "user",
  638. },
  639. {
  640. id: "zcodeagentmcp-global-exa",
  641. name: "exa",
  642. config: { type: "http", url: "https://mcp.exa.ai/mcp" },
  643. enabled: true,
  644. changed: false,
  645. status: "connected",
  646. toolCount: 2,
  647. source: "zcodeagentmcp",
  648. scope: "user",
  649. },
  650. {
  651. id: "claudeclimcp-global-context7",
  652. name: "context7",
  653. config: { type: "stdio", command: "npx", args: ["-y", "@upstash/context7-mcp"], timeoutMs: 3 },
  654. enabled: true,
  655. changed: true,
  656. status: "unknown",
  657. source: "claudeclimcp",
  658. scope: "user",
  659. },
  660. ],
  661. });
  662. useMcpStore.getState().beginServerStatusListRefresh();
  663. expect(useMcpStore.getState().servers[0]).toMatchObject({
  664. status: "connecting",
  665. error: undefined,
  666. toolCount: undefined,
  667. });
  668. expect(useMcpStore.getState().servers[1]).toMatchObject({
  669. status: "connected",
  670. toolCount: 2,
  671. });
  672. expect(useMcpStore.getState().servers[2]).toMatchObject({
  673. status: "unknown",
  674. source: "claudeclimcp",
  675. });
  676. });
  677. it("status-only 刷新开始时只推进 epoch,不改写现有展示态", () => {
  678. const authorization = {
  679. authorizationUrl: "https://oauth.example.test/authorize",
  680. startedAt: "2026-07-10T00:00:00.000Z",
  681. };
  682. useMcpStore.setState({
  683. servers: [
  684. {
  685. id: "zcodeagentmcp-global-pending",
  686. name: "pending",
  687. config: { type: "http", url: "https://mcp.example.test/pending" },
  688. enabled: true,
  689. changed: true,
  690. status: "unknown",
  691. authorization,
  692. error: "keep display state",
  693. toolCount: 3,
  694. source: "zcodeagentmcp",
  695. scope: "user",
  696. },
  697. ],
  698. });
  699. useMcpStore.getState().beginServerStatusListRefresh("status");
  700. expect(useMcpStore.getState().servers[0]).toMatchObject({
  701. authorization,
  702. changed: true,
  703. error: "keep display state",
  704. status: "unknown",
  705. toolCount: 3,
  706. });
  707. });
  708. it("status-only epoch 不会作废同时进行的 connect 结果", () => {
  709. useMcpStore.setState({
  710. servers: [
  711. {
  712. id: "zcodeagentmcp-global-new-server",
  713. name: "new-server",
  714. config: { type: "stdio", command: "new-server" },
  715. enabled: true,
  716. changed: true,
  717. status: "unknown",
  718. source: "zcodeagentmcp",
  719. scope: "user",
  720. },
  721. ],
  722. });
  723. const connectEpoch = useMcpStore.getState().beginServerStatusListRefresh("connect");
  724. useMcpStore.getState().beginServerStatusListRefresh("status");
  725. useMcpStore.getState().mergeServerStatusSnapshots(
  726. {
  727. "new-server": {
  728. status: "connected",
  729. transport: "stdio",
  730. toolCount: 1,
  731. updatedAt: "2026-07-10T00:00:00.000Z",
  732. },
  733. },
  734. connectEpoch,
  735. "connect",
  736. );
  737. expect(useMcpStore.getState().servers[0]).toMatchObject({
  738. changed: false,
  739. status: "connected",
  740. toolCount: 1,
  741. });
  742. });
  743. it("批量状态刷新失败时会把当前连接中的 ZCode Agent MCP 收口为错误", () => {
  744. useMcpStore.setState({
  745. servers: [
  746. {
  747. id: "zcodeagentmcp-global-broken",
  748. name: "broken",
  749. config: { type: "stdio", command: "missing-mcp-command" },
  750. enabled: true,
  751. changed: true,
  752. status: "unknown",
  753. source: "zcodeagentmcp",
  754. scope: "user",
  755. },
  756. ],
  757. });
  758. const epoch = useMcpStore.getState().beginServerStatusListRefresh();
  759. useMcpStore.getState().markServerStatusListRefreshFailed("agent unavailable", epoch);
  760. expect(useMcpStore.getState().servers[0]).toMatchObject({
  761. status: "error",
  762. error: "agent unavailable",
  763. toolCount: undefined,
  764. });
  765. });
  766. it("status-only 刷新失败时保留 pending snapshot 和现有连接态", () => {
  767. useMcpStore.setState({
  768. statusSnapshots: {
  769. local: {
  770. status: "connecting",
  771. transport: "http",
  772. toolCount: 0,
  773. updatedAt: "2026-07-10T00:00:00.000Z",
  774. authorization: {
  775. authorizationUrl: "https://oauth.example.test/local",
  776. startedAt: "2026-07-10T00:00:00.000Z",
  777. },
  778. },
  779. "plugin:canva:canva": {
  780. status: "connecting",
  781. transport: "http",
  782. toolCount: 0,
  783. updatedAt: "2026-07-10T00:00:00.000Z",
  784. authorization: {
  785. authorizationUrl: "https://oauth.example.test/plugin",
  786. startedAt: "2026-07-10T00:00:00.000Z",
  787. },
  788. },
  789. },
  790. servers: [
  791. {
  792. id: "zcodeagentmcp-global-local",
  793. name: "local",
  794. config: { type: "http", url: "https://mcp.example.test/local" },
  795. enabled: true,
  796. changed: false,
  797. status: "connecting",
  798. authorization: {
  799. authorizationUrl: "https://oauth.example.test/local",
  800. startedAt: "2026-07-10T00:00:00.000Z",
  801. },
  802. source: "zcodeagentmcp",
  803. scope: "user",
  804. },
  805. ],
  806. });
  807. const epoch = useMcpStore.getState().beginServerStatusListRefresh("status");
  808. useMcpStore
  809. .getState()
  810. .markServerStatusListRefreshFailed("temporary status failure", epoch, "status");
  811. expect(useMcpStore.getState().statusSnapshots).toMatchObject({
  812. local: {
  813. authorization: {
  814. authorizationUrl: "https://oauth.example.test/local",
  815. },
  816. },
  817. "plugin:canva:canva": {
  818. authorization: {
  819. authorizationUrl: "https://oauth.example.test/plugin",
  820. },
  821. },
  822. });
  823. expect(useMcpStore.getState().servers[0]).toMatchObject({
  824. status: "connecting",
  825. authorization: {
  826. authorizationUrl: "https://oauth.example.test/local",
  827. },
  828. });
  829. expect(useMcpStore.getState().servers[0]?.error).toBeUndefined();
  830. });
  831. it("批量状态结果缺失当前连接中的 server 时不会一直停在连接中", () => {
  832. useMcpStore.setState({
  833. servers: [
  834. {
  835. id: "zcodeagentmcp-global-broken",
  836. name: "broken",
  837. config: { type: "stdio", command: "missing-mcp-command" },
  838. enabled: true,
  839. changed: true,
  840. status: "unknown",
  841. source: "zcodeagentmcp",
  842. scope: "user",
  843. },
  844. ],
  845. });
  846. const epoch = useMcpStore.getState().beginServerStatusListRefresh();
  847. useMcpStore.getState().mergeServerStatusSnapshots({}, epoch);
  848. expect(useMcpStore.getState().servers[0]).toMatchObject({
  849. status: "error",
  850. error: undefined,
  851. failureKind: "status_unavailable",
  852. toolCount: undefined,
  853. });
  854. });
  855. it("迟到的批量状态刷新失败不会覆盖更新的连接状态", () => {
  856. useMcpStore.setState({
  857. servers: [
  858. {
  859. id: "zcodeagentmcp-global-broken",
  860. name: "broken",
  861. config: { type: "stdio", command: "missing-mcp-command" },
  862. enabled: true,
  863. changed: true,
  864. status: "unknown",
  865. source: "zcodeagentmcp",
  866. scope: "user",
  867. },
  868. ],
  869. });
  870. const oldEpoch = useMcpStore.getState().beginServerStatusListRefresh();
  871. useMcpStore.getState().beginServerStatusListRefresh();
  872. useMcpStore.getState().markServerStatusListRefreshFailed("old failure", oldEpoch);
  873. expect(useMcpStore.getState().servers[0]).toMatchObject({
  874. status: "connecting",
  875. error: undefined,
  876. });
  877. });
  878. it("更新 MCP 配置后会清理旧健康状态并重新标记 changed", async () => {
  879. const server = {
  880. source: "zcodeagentmcp" as const,
  881. scope: "user" as const,
  882. name: "context7",
  883. config: {
  884. type: "stdio" as const,
  885. command: "npx",
  886. args: ["-y", "@upstash/context7-mcp"],
  887. timeoutMs: 3,
  888. },
  889. enabled: true,
  890. };
  891. useMcpStore.setState({
  892. nativeServers: [server],
  893. servers: [
  894. {
  895. id: "zcodeagentmcp-global-context7",
  896. name: "context7",
  897. config: server.config,
  898. enabled: true,
  899. changed: false,
  900. status: "error",
  901. error: "MCP server context7 connection timed out after 3ms",
  902. source: "zcodeagentmcp",
  903. scope: "user",
  904. },
  905. ],
  906. });
  907. await useMcpStore.getState().updateScopedMcpServer("zcodeagentmcp", "context7", {
  908. ...server.config,
  909. timeoutMs: 30000,
  910. });
  911. expect(useMcpStore.getState().servers[0]).toMatchObject({
  912. config: expect.objectContaining({ timeoutMs: 30000 }),
  913. changed: true,
  914. status: "unknown",
  915. error: undefined,
  916. });
  917. });
  918. it("切换启用状态会先落盘再更新本地列表", async () => {
  919. let resolveSave!: () => void;
  920. const saveMcpToUserDirectory = vi.fn(
  921. () =>
  922. new Promise<{ success: true }>((resolve) => {
  923. resolveSave = () => resolve({ success: true });
  924. }),
  925. );
  926. setMcpStorePlatform({
  927. loadMcpFromUserDirectory: vi.fn(async () => ({ servers: [] })),
  928. migrateLegacyCommonMcp: vi.fn(async () => ({
  929. importedCount: 0,
  930. servers: {},
  931. skippedCount: 0,
  932. totalCount: 0,
  933. })),
  934. saveMcpToUserDirectory,
  935. });
  936. useMcpStore.setState({
  937. servers: [
  938. {
  939. id: "zcodeagentmcp-global-broken",
  940. name: "broken",
  941. config: { type: "stdio", command: "missing-mcp-command" },
  942. enabled: false,
  943. source: "zcodeagentmcp",
  944. scope: "user",
  945. status: "unknown",
  946. },
  947. ],
  948. });
  949. const toggle = useMcpStore.getState().toggleServer("zcodeagentmcp-global-broken", true);
  950. await Promise.resolve();
  951. expect(useMcpStore.getState().servers[0]?.enabled).toBe(false);
  952. expect(saveMcpToUserDirectory).toHaveBeenCalledWith(
  953. expect.objectContaining({
  954. action: "set-enabled",
  955. enabled: true,
  956. name: "broken",
  957. source: "zcodeagentmcp",
  958. }),
  959. );
  960. resolveSave();
  961. await toggle;
  962. expect(useMcpStore.getState().servers[0]?.enabled).toBe(true);
  963. });
  964. });