mcp.test.ts 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  1. import { delimiter, dirname } from "node:path";
  2. import { beforeEach, describe, expect, it, vi } from "vitest";
  3. import { UnauthorizedError } from "@modelcontextprotocol/client";
  4. import { ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY } from "@zcode/shared";
  5. import type { SharedZCodeCredentialStore } from "../src/auth/shared-credentials.js";
  6. const {
  7. capturedClientInfo,
  8. capturedClients,
  9. capturedHttpOptions,
  10. capturedSseOptions,
  11. capturedStdioOptions,
  12. capturedStdioStderrHandlers,
  13. capturedClientOptions,
  14. clientCloseMock,
  15. clientCallToolMock,
  16. clientConnectMock,
  17. clientListToolsMock,
  18. clientPingMock,
  19. transportCloseMock,
  20. transportFinishAuthMock,
  21. authMock,
  22. } = vi.hoisted(() => ({
  23. capturedClientInfo: [] as Array<{ name: string; version: string }>,
  24. capturedClients: [] as Array<{ onclose?: () => void }>,
  25. capturedHttpOptions: [] as unknown[],
  26. capturedSseOptions: [] as unknown[],
  27. capturedStdioOptions: [] as unknown[],
  28. capturedStdioStderrHandlers: [] as Array<(chunk: Buffer) => void>,
  29. capturedClientOptions: [] as unknown[],
  30. clientCloseMock: vi.fn(async () => {}),
  31. clientCallToolMock: vi.fn(async () => ({
  32. content: [{ type: "text", text: "ok" }],
  33. })),
  34. clientConnectMock: vi.fn(async () => {}),
  35. clientListToolsMock: vi.fn(async () => ({ tools: [] })),
  36. clientPingMock: vi.fn(async () => ({})),
  37. transportCloseMock: vi.fn(async () => {}),
  38. transportFinishAuthMock: vi.fn(async () => {}),
  39. authMock: vi.fn(async () => "AUTHORIZED" as const),
  40. }));
  41. vi.mock("@modelcontextprotocol/client", async (importOriginal) => {
  42. const actual = await importOriginal<typeof import("@modelcontextprotocol/client")>();
  43. return {
  44. ...actual,
  45. auth: authMock,
  46. Client: class {
  47. readonly close = clientCloseMock;
  48. readonly callTool = clientCallToolMock;
  49. readonly connect = clientConnectMock;
  50. readonly listTools = clientListToolsMock;
  51. readonly ping = clientPingMock;
  52. onclose?: () => void;
  53. constructor(info: { name: string; version: string }, options?: unknown) {
  54. capturedClientInfo.push(info);
  55. capturedClientOptions.push(options);
  56. capturedClients.push(this);
  57. }
  58. getProtocolEra() {
  59. const options = capturedClientOptions.at(-1) as {
  60. versionNegotiation?: { mode?: unknown };
  61. };
  62. return options?.versionNegotiation?.mode === "legacy" ? "legacy" : "modern";
  63. }
  64. getNegotiatedProtocolVersion() {
  65. const options = capturedClientOptions.at(-1) as {
  66. versionNegotiation?: { mode?: unknown };
  67. };
  68. return options?.versionNegotiation?.mode === "legacy" ? "2025-11-25" : "2026-07-28";
  69. }
  70. },
  71. SSEClientTransport: class {
  72. readonly close = transportCloseMock;
  73. readonly finishAuth = transportFinishAuthMock;
  74. constructor(_url: URL, options: unknown) {
  75. capturedSseOptions.push(options);
  76. }
  77. },
  78. StreamableHTTPClientTransport: class {
  79. readonly close = transportCloseMock;
  80. readonly finishAuth = transportFinishAuthMock;
  81. constructor(_url: URL, options: unknown) {
  82. capturedHttpOptions.push(options);
  83. }
  84. },
  85. };
  86. });
  87. vi.mock("@modelcontextprotocol/client/stdio", () => ({
  88. StdioClientTransport: class {
  89. readonly close = transportCloseMock;
  90. readonly pid = 42_424;
  91. readonly stderr = {
  92. on: vi.fn((event: "data", handler: (chunk: Buffer) => void) => {
  93. if (event === "data") capturedStdioStderrHandlers.push(handler);
  94. }),
  95. };
  96. constructor(options: unknown) {
  97. capturedStdioOptions.push(options);
  98. }
  99. },
  100. }));
  101. import { createMcpAdapter } from "../src/mcp/index.js";
  102. import { createMcpTelemetryTracker } from "../src/mcp/telemetry.js";
  103. /**
  104. * 把 Phase 1 建连做成认证失败,并接管 Phase 2 的 `auth()`:调用 provider 的
  105. * `redirectToAuthorization()` 暴露授权 URL,然后阻塞在 gate 上,直到测试调用 `release()`。
  106. *
  107. * 修复原因:授权 URL 的归属已经从「Phase 1 provider 自己 redirect」改为「Phase 2 事务发布」,
  108. * 所以这些用例必须走 connect 失败 → 分类 → Phase 2 这条新链路。
  109. */
  110. function stubInteractiveAuthorization(
  111. authorizationUrl: string,
  112. beforeAuthorization?: Promise<void>,
  113. ): { release: () => void; ready: Promise<void> } {
  114. let markReady!: () => void;
  115. const ready = new Promise<void>((resolve) => {
  116. markReady = resolve;
  117. });
  118. let release!: () => void;
  119. const gate = new Promise<void>((resolve) => {
  120. release = resolve;
  121. });
  122. let connectAttempts = 0;
  123. clientConnectMock.mockImplementation(async () => {
  124. connectAttempts += 1;
  125. // 第一次建连以确定性认证错误失败,触发 Phase 2;授权完成后的重连必须成功。
  126. if (connectAttempts === 1) throw new UnauthorizedError();
  127. });
  128. authMock.mockImplementation(async (provider: unknown) => {
  129. const interactiveProvider = provider as {
  130. redirectToAuthorization(url: URL): Promise<void>;
  131. };
  132. await beforeAuthorization;
  133. await interactiveProvider.redirectToAuthorization(new URL(authorizationUrl));
  134. markReady();
  135. await gate;
  136. return "AUTHORIZED" as const;
  137. });
  138. return { release, ready };
  139. }
  140. async function observePromiseWithin<T>(
  141. promise: Promise<T>,
  142. timeoutMs: number,
  143. ): Promise<
  144. | { status: "fulfilled"; value: T }
  145. | { reason: unknown; status: "rejected" }
  146. | { status: "pending" }
  147. > {
  148. let timeoutId: ReturnType<typeof setTimeout> | undefined;
  149. const observed = promise.then(
  150. (value) => ({ status: "fulfilled" as const, value }),
  151. (reason: unknown) => ({ reason, status: "rejected" as const }),
  152. );
  153. try {
  154. return await Promise.race([
  155. observed,
  156. new Promise<{ status: "pending" }>((resolve) => {
  157. timeoutId = setTimeout(() => resolve({ status: "pending" }), timeoutMs);
  158. }),
  159. ]);
  160. } finally {
  161. if (timeoutId !== undefined) clearTimeout(timeoutId);
  162. }
  163. }
  164. describe("createMcpAdapter", () => {
  165. beforeEach(() => {
  166. capturedClientInfo.length = 0;
  167. capturedHttpOptions.length = 0;
  168. capturedSseOptions.length = 0;
  169. capturedStdioOptions.length = 0;
  170. capturedStdioStderrHandlers.length = 0;
  171. capturedClientOptions.length = 0;
  172. capturedClients.length = 0;
  173. clientCloseMock.mockClear();
  174. clientCallToolMock.mockClear();
  175. clientConnectMock.mockClear();
  176. clientListToolsMock.mockClear();
  177. clientPingMock.mockClear();
  178. clientPingMock.mockResolvedValue({});
  179. transportCloseMock.mockClear();
  180. transportFinishAuthMock.mockClear();
  181. authMock.mockClear();
  182. authMock.mockResolvedValue("AUTHORIZED");
  183. clientConnectMock.mockResolvedValue(undefined);
  184. clientListToolsMock.mockResolvedValue({ tools: [] });
  185. clientCallToolMock.mockResolvedValue({
  186. content: [{ type: "text", text: "ok" }],
  187. });
  188. });
  189. it("close waits for cancelled handshake resource cleanup before returning", async () => {
  190. const started = Promise.withResolvers<void>();
  191. const cleanupStarted = Promise.withResolvers<void>();
  192. const cleaned = Promise.withResolvers<void>();
  193. clientConnectMock.mockImplementationOnce(async () => {
  194. started.resolve();
  195. await new Promise(() => {});
  196. });
  197. clientCloseMock.mockImplementationOnce(async () => {
  198. cleanupStarted.resolve();
  199. await cleaned.promise;
  200. });
  201. const adapter = createMcpAdapter();
  202. const connecting = adapter.connectServer("slow", {
  203. type: "http",
  204. url: "https://mcp.example.test/mcp",
  205. });
  206. await started.promise;
  207. let settled = false;
  208. const closing = adapter.close().then(() => {
  209. settled = true;
  210. });
  211. await cleanupStarted.promise;
  212. for (let i = 0; i < 5; i++) await Promise.resolve();
  213. expect(settled).toBe(false);
  214. cleaned.resolve();
  215. await closing;
  216. await connecting;
  217. expect(await adapter.status()).toEqual({});
  218. });
  219. it("waits for the existing App connection without exposing a premature snapshot or reconnecting", async () => {
  220. const gate = Promise.withResolvers<void>();
  221. clientConnectMock.mockImplementationOnce(() => gate.promise);
  222. const adapter = createMcpAdapter();
  223. const connecting = adapter.connectServer("fixture", { type: "stdio", command: "node" });
  224. await vi.waitFor(() => expect(clientConnectMock).toHaveBeenCalledOnce());
  225. expect(adapter.appConnectionSnapshot?.("fixture")).toBeNull();
  226. const settled = vi.fn();
  227. const opening = adapter.waitForAppConnection!("fixture").then(settled);
  228. await Promise.resolve();
  229. expect(settled).not.toHaveBeenCalled();
  230. gate.resolve();
  231. await connecting;
  232. await opening;
  233. expect(settled).toHaveBeenCalledWith(adapter.appConnectionSnapshot?.("fixture"));
  234. expect(settled.mock.calls[0]?.[0]).not.toBeNull();
  235. expect(clientConnectMock).toHaveBeenCalledOnce();
  236. await adapter.close();
  237. });
  238. it("does not issue an App connection for an absent or failed server", async () => {
  239. const adapter = createMcpAdapter();
  240. expect(await adapter.waitForAppConnection!("missing")).toBeNull();
  241. clientConnectMock.mockRejectedValueOnce(new Error("fixture startup failure"));
  242. await adapter.connectServer("fixture", { type: "stdio", command: "node" });
  243. expect(await adapter.waitForAppConnection!("fixture")).toBeNull();
  244. expect(clientConnectMock).toHaveBeenCalledOnce();
  245. await adapter.close();
  246. });
  247. it("rejects an App startup waiter after the connection generation is replaced", async () => {
  248. const gate = Promise.withResolvers<void>();
  249. clientConnectMock.mockImplementationOnce(() => gate.promise);
  250. const adapter = createMcpAdapter();
  251. const config = { type: "stdio" as const, command: "node" };
  252. const connecting = adapter.connectServer("fixture", config);
  253. await vi.waitFor(() => expect(clientConnectMock).toHaveBeenCalledOnce());
  254. const opening = adapter.waitForAppConnection!("fixture");
  255. await adapter.connectServer("fixture", config);
  256. gate.resolve();
  257. await connecting;
  258. expect(await opening).toBeNull();
  259. expect(adapter.appConnectionSnapshot?.("fixture")).not.toBeNull();
  260. await adapter.close();
  261. });
  262. it("forwards runtime scope, session, turn, and trace context through MCP request metadata", async () => {
  263. const adapter = createMcpAdapter();
  264. await adapter.connectServer("node_repl", {
  265. command: "node",
  266. type: "stdio",
  267. });
  268. await adapter.callTool({
  269. arguments: { code: "1 + 1" },
  270. serverName: "node_repl",
  271. toolName: "js",
  272. runtimeScope: "subagent",
  273. trace: {
  274. parentSpanId: "parent-1",
  275. sessionId: "session-1" as never,
  276. spanId: "span-1",
  277. traceId: "trace-1" as never,
  278. turnId: "turn-1" as never,
  279. },
  280. });
  281. expect(clientCallToolMock).toHaveBeenCalledWith(
  282. {
  283. arguments: { code: "1 + 1" },
  284. name: "js",
  285. _meta: {
  286. "com.zcode/request-context": {
  287. parent_span_id: "parent-1",
  288. runtime_scope: "subagent",
  289. session_id: "session-1",
  290. span_id: "span-1",
  291. trace_id: "trace-1",
  292. turn_id: "turn-1",
  293. },
  294. parent_span_id: "parent-1",
  295. runtime_scope: "subagent",
  296. session_id: "session-1",
  297. span_id: "span-1",
  298. trace_id: "trace-1",
  299. turn_id: "turn-1",
  300. },
  301. },
  302. expect.objectContaining({ resetTimeoutOnProgress: true }),
  303. );
  304. });
  305. it("forwards the root session of a subagent call through MCP request metadata", async () => {
  306. const adapter = createMcpAdapter();
  307. await adapter.connectServer("node_repl", { command: "node", type: "stdio" });
  308. await adapter.callTool({
  309. arguments: { code: "1 + 1" },
  310. serverName: "node_repl",
  311. toolName: "js",
  312. runtimeScope: "subagent",
  313. trace: {
  314. rootSessionId: "session-1" as never,
  315. sessionId: "subagent-1" as never,
  316. traceId: "trace-1" as never,
  317. },
  318. });
  319. const meta = clientCallToolMock.mock.calls.at(-1)?.[0]._meta;
  320. expect(meta).toMatchObject({ root_session_id: "session-1", session_id: "subagent-1" });
  321. expect(meta["com.zcode/request-context"]).toMatchObject({
  322. root_session_id: "session-1",
  323. session_id: "subagent-1",
  324. });
  325. });
  326. it("uses the injected client version for MCP initialize", async () => {
  327. const adapter = createMcpAdapter({ clientVersion: "9.8.7" });
  328. await adapter.connectServer("demo", {
  329. command: "node",
  330. type: "stdio",
  331. });
  332. expect(capturedClientInfo).toEqual([
  333. {
  334. name: "zcode",
  335. version: "9.8.7",
  336. },
  337. ]);
  338. });
  339. it("logs the configured negotiation policy and actual MCP protocol version", async () => {
  340. const infoMock = vi.fn();
  341. const logger = {
  342. child: vi.fn(),
  343. debug: vi.fn(),
  344. error: vi.fn(),
  345. info: infoMock,
  346. warn: vi.fn(),
  347. };
  348. logger.child.mockReturnValue(logger);
  349. const adapter = createMcpAdapter({
  350. clientName: "zcode-test",
  351. clientVersion: "9.8.7",
  352. connectionContext: {
  353. mcpConnectionId: "connection-session-1",
  354. mcpIsolation: "session",
  355. sessionId: "session-1",
  356. workspaceKey: "workspace-1",
  357. },
  358. logger,
  359. });
  360. await adapter.connectServer("auto-modern", {
  361. command: "node",
  362. type: "stdio",
  363. });
  364. await adapter.connectServer("explicit-legacy", {
  365. command: "node",
  366. protocolVersion: "legacy",
  367. type: "stdio",
  368. });
  369. expect(infoMock).toHaveBeenCalledWith(
  370. "MCP server connected",
  371. expect.objectContaining({
  372. event: "mcp.server.connected",
  373. mcpClientName: "zcode-test",
  374. mcpClientVersion: "9.8.7",
  375. mcpConnectionId: "connection-session-1",
  376. mcpIsolation: "session",
  377. mcpProtocolEra: "modern",
  378. mcpProtocolVersion: "2026-07-28",
  379. mcpServerName: "auto-modern",
  380. mcpTransportPid: 42_424,
  381. mcpVersionNegotiationMode: "auto",
  382. sessionId: "session-1",
  383. workspaceKey: "workspace-1",
  384. }),
  385. );
  386. expect(infoMock).toHaveBeenCalledWith(
  387. "MCP server connected",
  388. expect.objectContaining({
  389. event: "mcp.server.connected",
  390. mcpClientName: "zcode-test",
  391. mcpClientVersion: "9.8.7",
  392. mcpProtocolEra: "legacy",
  393. mcpProtocolVersion: "2025-11-25",
  394. mcpServerName: "explicit-legacy",
  395. mcpVersionNegotiationMode: "legacy",
  396. }),
  397. );
  398. });
  399. it("defaults ordinary MCP servers to dual-era auto while keeping explicit era pins", async () => {
  400. const adapter = createMcpAdapter();
  401. await adapter.connectServer("browser_use", {
  402. command: "node",
  403. protocolVersion: "2026-07-28",
  404. timeoutMs: 600_000,
  405. type: "stdio",
  406. });
  407. await adapter.connectServer("default-stdio", {
  408. command: "node",
  409. type: "stdio",
  410. });
  411. await adapter.connectServer("default-http", {
  412. type: "http",
  413. url: "https://mcp.example.test",
  414. });
  415. await adapter.connectServer("auto-http", {
  416. protocolVersion: "auto",
  417. timeoutMs: 2_000,
  418. type: "http",
  419. url: "https://mcp.example.test/auto",
  420. });
  421. await adapter.connectServer("legacy-http", {
  422. protocolVersion: "legacy",
  423. type: "http",
  424. url: "https://mcp.example.test/legacy",
  425. });
  426. await adapter.connectServer("legacy-sse", {
  427. type: "sse",
  428. url: "https://mcp.example.test/sse",
  429. });
  430. expect(
  431. capturedClientOptions.map((options) => ({
  432. versionNegotiation: (options as { versionNegotiation?: unknown }).versionNegotiation,
  433. })),
  434. ).toEqual([
  435. {
  436. versionNegotiation: {
  437. mode: { pin: "2026-07-28" },
  438. probe: { timeoutMs: 600_000 },
  439. },
  440. },
  441. { versionNegotiation: { mode: "auto", probe: { timeoutMs: 5_000 } } },
  442. { versionNegotiation: { mode: "auto", probe: { timeoutMs: 5_000 } } },
  443. { versionNegotiation: { mode: "auto", probe: { timeoutMs: 1_000 } } },
  444. { versionNegotiation: { mode: "legacy" } },
  445. { versionNegotiation: { mode: "legacy" } },
  446. ]);
  447. // MCP Apps:每个 client 都宣告可渲染的 UI mimeType,server 据此决定是否下发 ui 资源。
  448. for (const options of capturedClientOptions) {
  449. expect(options).toMatchObject({
  450. capabilities: {
  451. extensions: {
  452. "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] },
  453. },
  454. },
  455. });
  456. }
  457. });
  458. it("preserves non-object structuredContent from MCP 2026-07-28", async () => {
  459. clientCallToolMock.mockResolvedValue({
  460. content: [{ type: "text", text: "ok" }],
  461. structuredContent: ["first", 2, true],
  462. });
  463. const adapter = createMcpAdapter();
  464. await adapter.connectServer("modern", {
  465. command: "node",
  466. protocolVersion: "2026-07-28",
  467. type: "stdio",
  468. });
  469. await expect(
  470. adapter.callTool({
  471. serverName: "modern",
  472. toolName: "array-result",
  473. }),
  474. ).resolves.toMatchObject({
  475. structuredContent: ["first", 2, true],
  476. });
  477. });
  478. it("projects server timeout onto listed MCP tool descriptors", async () => {
  479. clientListToolsMock.mockResolvedValue({
  480. tools: [
  481. {
  482. name: "long-task",
  483. inputSchema: {
  484. type: "object",
  485. properties: {},
  486. },
  487. },
  488. ],
  489. });
  490. const adapter = createMcpAdapter();
  491. await adapter.connectServer("demo", {
  492. command: "node",
  493. timeoutMs: 900_000,
  494. type: "stdio",
  495. });
  496. await expect(adapter.listTools()).resolves.toMatchObject([
  497. {
  498. serverName: "demo",
  499. toolName: "long-task",
  500. name: "mcp__demo__long-task",
  501. timeoutMs: 900_000,
  502. },
  503. ]);
  504. });
  505. it("reports connecting status while an MCP server is still starting", async () => {
  506. let resolveConnect!: () => void;
  507. clientConnectMock.mockImplementation(
  508. () =>
  509. new Promise<void>((resolve) => {
  510. resolveConnect = resolve;
  511. }),
  512. );
  513. const adapter = createMcpAdapter();
  514. const connect = adapter.connectServer("demo", {
  515. command: "node",
  516. type: "stdio",
  517. });
  518. await Promise.resolve();
  519. await expect(adapter.status()).resolves.toMatchObject({
  520. demo: {
  521. status: "connecting",
  522. transport: "stdio",
  523. toolCount: 0,
  524. },
  525. });
  526. resolveConnect();
  527. await expect(connect).resolves.toMatchObject({
  528. status: "connected",
  529. toolCount: 0,
  530. });
  531. });
  532. it("bounds callTool waiting for a shared startup connection without cancelling it", async () => {
  533. let resolveConnect!: () => void;
  534. clientConnectMock.mockImplementation(
  535. () =>
  536. new Promise<void>((resolve) => {
  537. resolveConnect = resolve;
  538. }),
  539. );
  540. const adapter = createMcpAdapter();
  541. const connect = adapter.connectServer("demo", {
  542. command: "node",
  543. type: "stdio",
  544. });
  545. await Promise.resolve();
  546. const call = adapter.callTool(
  547. {
  548. serverName: "demo",
  549. toolName: "slow-start",
  550. },
  551. { timeoutMs: 20 },
  552. );
  553. try {
  554. await expect(observePromiseWithin(call, 200)).resolves.toMatchObject({
  555. reason: {
  556. name: "McpTimeoutError",
  557. },
  558. status: "rejected",
  559. });
  560. await expect(adapter.status()).resolves.toMatchObject({
  561. demo: { status: "connecting" },
  562. });
  563. expect(clientCallToolMock).not.toHaveBeenCalled();
  564. } finally {
  565. resolveConnect();
  566. await Promise.allSettled([connect, call]);
  567. await adapter.close();
  568. }
  569. await expect(adapter.status()).resolves.toEqual({});
  570. });
  571. it("includes sanitized recent stdio stderr when MCP server connection fails", async () => {
  572. const debugMock = vi.fn();
  573. const warnMock = vi.fn();
  574. const logger = {
  575. child: vi.fn(),
  576. debug: debugMock,
  577. error: vi.fn(),
  578. info: vi.fn(),
  579. warn: warnMock,
  580. };
  581. logger.child.mockReturnValue(logger);
  582. clientConnectMock.mockImplementation(async () => {
  583. capturedStdioStderrHandlers[0]?.(
  584. Buffer.from(
  585. [
  586. "MYSQL_PASS=super-secret",
  587. "Authorization: Bearer live-token",
  588. "fatal: database refused connection",
  589. ].join("\n"),
  590. ),
  591. );
  592. throw new Error("MCP error -32000: Connection closed");
  593. });
  594. const adapter = createMcpAdapter({ logger });
  595. await expect(
  596. adapter.connectServer("mysql-local", {
  597. command: "node",
  598. type: "stdio",
  599. }),
  600. ).resolves.toMatchObject({
  601. error: "MCP error -32000: Connection closed",
  602. status: "failed",
  603. });
  604. expect(debugMock).toHaveBeenCalledWith(
  605. "MCP stdio stderr",
  606. expect.objectContaining({
  607. stderr: expect.stringContaining("fatal: database refused connection"),
  608. }),
  609. );
  610. expect(warnMock).toHaveBeenCalledWith(
  611. "MCP server connection failed",
  612. expect.objectContaining({
  613. error: "MCP error -32000: Connection closed",
  614. event: "mcp.server.failed",
  615. stderr: expect.stringContaining("fatal: database refused connection"),
  616. }),
  617. );
  618. const warnContext = warnMock.mock.calls[0]?.[1] as { stderr?: string };
  619. expect(warnContext.stderr).toContain("MYSQL_PASS=[Redacted]");
  620. expect(warnContext.stderr).toContain("Authorization: Bearer [Redacted]");
  621. expect(warnContext.stderr).not.toContain("super-secret");
  622. expect(warnContext.stderr).not.toContain("live-token");
  623. });
  624. it("marks the record disconnected and logs recent stderr when the transport closes unexpectedly", async () => {
  625. const warnMock = vi.fn();
  626. const logger = {
  627. child: vi.fn(),
  628. debug: vi.fn(),
  629. error: vi.fn(),
  630. info: vi.fn(),
  631. warn: warnMock,
  632. };
  633. logger.child.mockReturnValue(logger);
  634. const telemetryEvents: Array<{ kind: string; mcpInstanceId?: string }> = [];
  635. const telemetry = createMcpTelemetryTracker({
  636. idSalt: "device-a",
  637. onEvent: (event) => telemetryEvents.push(event),
  638. randomId: () => "mcp-instance-1",
  639. });
  640. telemetry.registerConnection({
  641. connectionId: "connection-1",
  642. isolation: "session",
  643. serverName: "node_repl",
  644. });
  645. telemetry.acquireOwner({
  646. connectionId: "connection-1",
  647. ownerId: "lease-1",
  648. sessionId: "session-1",
  649. });
  650. const adapter = createMcpAdapter({
  651. connectionContext: {
  652. mcpConnectionId: "connection-1",
  653. mcpIsolation: "session",
  654. sessionId: "session-1",
  655. },
  656. logger,
  657. telemetry,
  658. });
  659. await adapter.connectServer("node_repl", {
  660. command: "node",
  661. type: "stdio",
  662. });
  663. capturedStdioStderrHandlers[0]?.(
  664. Buffer.from("node_repl uncaughtException: boom from async timer\n"),
  665. );
  666. capturedClients.at(-1)?.onclose?.();
  667. expect(warnMock).toHaveBeenCalledWith(
  668. "MCP server connection lost",
  669. expect.objectContaining({
  670. event: "mcp.server.connection_lost",
  671. mcpServerName: "node_repl",
  672. mcpTransportPid: 42_424,
  673. stderr: expect.stringContaining("boom from async timer"),
  674. }),
  675. );
  676. const statuses = await adapter.status();
  677. expect(statuses.node_repl?.status).toBe("disconnected");
  678. expect(statuses.node_repl?.failureKind).toBe("unexpected_disconnect");
  679. expect(telemetryEvents.map((event) => [event.kind, event.mcpInstanceId])).toEqual([
  680. ["process_start", "mcp-instance-1"],
  681. ["process_crash", "mcp-instance-1"],
  682. ]);
  683. });
  684. it("does not report connection_lost when the server is closed deliberately", async () => {
  685. const warnMock = vi.fn();
  686. const logger = {
  687. child: vi.fn(),
  688. debug: vi.fn(),
  689. error: vi.fn(),
  690. info: vi.fn(),
  691. warn: warnMock,
  692. };
  693. logger.child.mockReturnValue(logger);
  694. const adapter = createMcpAdapter({ logger });
  695. await adapter.connectServer("node_repl", {
  696. command: "node",
  697. type: "stdio",
  698. });
  699. await adapter.disconnectServer("node_repl");
  700. capturedClients.at(-1)?.onclose?.();
  701. expect(warnMock).not.toHaveBeenCalledWith("MCP server connection lost", expect.anything());
  702. });
  703. // Bugfix 回归:HTTP/SSE MCP 被停掉不会派发 onclose,status() 会一直停在 connected。
  704. // 设置页刷新依赖 pingServer 把这种无声死亡暴露出来。
  705. it("keeps the server connected when the ping succeeds", async () => {
  706. const adapter = createMcpAdapter();
  707. await adapter.connectServer("official_tools", {
  708. type: "http",
  709. url: "https://mcp.example/mcp",
  710. });
  711. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(true);
  712. expect((await adapter.status()).official_tools?.status).toBe("connected");
  713. });
  714. it("marks the server disconnected when the ping hits a dead transport", async () => {
  715. const warnMock = vi.fn();
  716. const logger = {
  717. child: vi.fn(),
  718. debug: vi.fn(),
  719. error: vi.fn(),
  720. info: vi.fn(),
  721. warn: warnMock,
  722. };
  723. logger.child.mockReturnValue(logger);
  724. const adapter = createMcpAdapter({ logger });
  725. await adapter.connectServer("official_tools", {
  726. type: "http",
  727. url: "https://mcp.example/mcp",
  728. });
  729. // SDK 本地错误用字符串 code(REQUEST_TIMEOUT / CONNECTION_CLOSED …)。
  730. clientPingMock.mockRejectedValue(
  731. Object.assign(new Error("Request timed out"), { code: "REQUEST_TIMEOUT" }),
  732. );
  733. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(false);
  734. expect((await adapter.status()).official_tools).toMatchObject({
  735. failureKind: "unexpected_disconnect",
  736. status: "disconnected",
  737. });
  738. expect(warnMock).toHaveBeenCalledWith(
  739. "MCP server ping failed",
  740. expect.objectContaining({
  741. event: "mcp.server.ping.failed",
  742. mcpServerName: "official_tools",
  743. }),
  744. );
  745. });
  746. it("treats a JSON-RPC error answer as a live connection", async () => {
  747. const adapter = createMcpAdapter();
  748. await adapter.connectServer("official_tools", {
  749. type: "http",
  750. url: "https://mcp.example/mcp",
  751. });
  752. // server 回了 method-not-found:请求走通了,连接是活的,不能据此拆连接。
  753. clientPingMock.mockRejectedValue(
  754. Object.assign(new Error("Method not found"), { code: -32_601 }),
  755. );
  756. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(true);
  757. expect((await adapter.status()).official_tools?.status).toBe("connected");
  758. });
  759. it("reports an unknown server as not alive", async () => {
  760. const adapter = createMcpAdapter();
  761. await expect(adapter.pingServer?.("missing")).resolves.toBe(false);
  762. });
  763. it("reconnects and retries once when the tool call hits a dead transport", async () => {
  764. const adapter = createMcpAdapter();
  765. await adapter.connectServer("node_repl", {
  766. command: "node",
  767. type: "stdio",
  768. });
  769. clientCallToolMock
  770. .mockRejectedValueOnce(new Error("Not connected"))
  771. .mockResolvedValueOnce({ content: [{ type: "text", text: "revived" }] });
  772. const result = await adapter.callTool({
  773. arguments: { code: "1 + 1" },
  774. serverName: "node_repl",
  775. toolName: "js",
  776. });
  777. expect(result.content).toEqual([{ type: "text", text: "revived" }]);
  778. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  779. expect(clientCallToolMock).toHaveBeenCalledTimes(2);
  780. });
  781. it("reconnects before calling when the record was already marked disconnected", async () => {
  782. const adapter = createMcpAdapter();
  783. await adapter.connectServer("node_repl", {
  784. command: "node",
  785. type: "stdio",
  786. });
  787. capturedClients.at(-1)?.onclose?.();
  788. expect((await adapter.status()).node_repl?.status).toBe("disconnected");
  789. const result = await adapter.callTool({
  790. arguments: { code: "1 + 1" },
  791. serverName: "node_repl",
  792. toolName: "js",
  793. });
  794. expect(result.content).toEqual([{ type: "text", text: "ok" }]);
  795. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  796. expect((await adapter.status()).node_repl?.status).toBe("connected");
  797. });
  798. it("surfaces the original error when reconnection also fails", async () => {
  799. const adapter = createMcpAdapter();
  800. await adapter.connectServer("node_repl", {
  801. command: "node",
  802. type: "stdio",
  803. });
  804. clientCallToolMock.mockRejectedValue(new Error("Not connected"));
  805. clientConnectMock.mockRejectedValue(new Error("spawn ENOENT"));
  806. await expect(
  807. adapter.callTool({
  808. arguments: { code: "1 + 1" },
  809. serverName: "node_repl",
  810. toolName: "js",
  811. }),
  812. ).rejects.toThrow(/Not connected/);
  813. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  814. });
  815. it("injects unified network env into stdio MCP transports", async () => {
  816. const adapter = createMcpAdapter({
  817. env: {
  818. PATH: dirname(process.execPath),
  819. ZCODE_AGENT_CA_CERT: "/tmp/root-ca.pem",
  820. },
  821. network: {
  822. httpProxy: "127.0.0.1:8888",
  823. noProxy: "localhost,127.0.0.1",
  824. },
  825. });
  826. await adapter.connectServer("demo", {
  827. command: "node",
  828. env: {
  829. MCP_TOKEN: "secret",
  830. },
  831. type: "stdio",
  832. });
  833. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  834. expect(options.env).toMatchObject({
  835. ALL_PROXY: "http://127.0.0.1:8888",
  836. CURL_CA_BUNDLE: "/tmp/root-ca.pem",
  837. GIT_SSL_CAINFO: "/tmp/root-ca.pem",
  838. HTTPS_PROXY: "http://127.0.0.1:8888",
  839. HTTP_PROXY: "http://127.0.0.1:8888",
  840. MCP_TOKEN: "secret",
  841. NODE_EXTRA_CA_CERTS: "/tmp/root-ca.pem",
  842. NO_PROXY: "localhost,127.0.0.1",
  843. // MCP 会补齐 Node 目录;本测试使用已含 Node 的 PATH,避免依赖测试机的 /bin。
  844. PATH: dirname(process.execPath),
  845. REQUESTS_CA_BUNDLE: "/tmp/root-ca.pem",
  846. SSL_CERT_FILE: "/tmp/root-ca.pem",
  847. all_proxy: "http://127.0.0.1:8888",
  848. http_proxy: "http://127.0.0.1:8888",
  849. https_proxy: "http://127.0.0.1:8888",
  850. no_proxy: "localhost,127.0.0.1",
  851. });
  852. });
  853. it("appends the injected node fallback after the server env", async () => {
  854. const resolve = vi.fn(async () => ({
  855. binDir: "/fallback/bin",
  856. env: { ZCODE_NODE_FALLBACK_EXEC_PATH: "/electron" },
  857. }));
  858. const adapter = createMcpAdapter({
  859. env: { PATH: dirname(process.execPath) },
  860. nodeFallback: { resolve },
  861. });
  862. await adapter.connectServer("demo", {
  863. command: "node",
  864. // 插件自带 PATH 会整体替换宿主 PATH;fallback 仍须追加在它后面。
  865. env: { PATH: "/plugin/bin" },
  866. type: "stdio",
  867. });
  868. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  869. expect(options.env?.PATH).toBe(["/plugin/bin", "/fallback/bin"].join(delimiter));
  870. expect(options.env?.ZCODE_NODE_FALLBACK_EXEC_PATH).toBe("/electron");
  871. expect(resolve).toHaveBeenCalledTimes(1);
  872. });
  873. it("restores captured user network env into stdio MCP transports", async () => {
  874. const adapter = createMcpAdapter({
  875. env: {
  876. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  877. NODE_EXTRA_CA_CERTS: "/tmp/user-ca.pem",
  878. http_proxy: "http://user-proxy:8080",
  879. }),
  880. PATH: dirname(process.execPath),
  881. },
  882. network: {},
  883. });
  884. await adapter.connectServer("demo", {
  885. command: "node",
  886. type: "stdio",
  887. });
  888. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  889. expect(options.env).toMatchObject({
  890. NODE_EXTRA_CA_CERTS: "/tmp/user-ca.pem",
  891. PATH: dirname(process.execPath),
  892. http_proxy: "http://user-proxy:8080",
  893. });
  894. expect(options.env?.[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
  895. });
  896. it("passes proxy-aware fetch into HTTP and SSE MCP transports", async () => {
  897. const adapter = createMcpAdapter({
  898. env: {
  899. ZCODE_HTTP_PROXY: "http://127.0.0.1:8888",
  900. },
  901. network: {},
  902. });
  903. await adapter.connectServer("http-demo", {
  904. type: "http",
  905. url: "https://mcp.example.test",
  906. });
  907. await adapter.connectServer("sse-demo", {
  908. type: "sse",
  909. url: "https://mcp.example.test/sse",
  910. });
  911. expect(capturedHttpOptions[0]).toMatchObject({
  912. fetch: expect.any(Function),
  913. });
  914. expect(capturedSseOptions[0]).toMatchObject({
  915. fetch: expect.any(Function),
  916. });
  917. await adapter.close();
  918. });
  919. it("passes a pure token AuthProvider into bare HTTP and SSE MCP transports", async () => {
  920. const adapter = createMcpAdapter();
  921. await adapter.connectServer("http-demo", {
  922. type: "http",
  923. url: "https://mcp.example.test",
  924. });
  925. await adapter.connectServer("sse-demo", {
  926. type: "sse",
  927. url: "https://mcp.example.test/sse",
  928. });
  929. const providers = [
  930. (capturedHttpOptions[0] as { authProvider?: Record<string, unknown> }).authProvider,
  931. (capturedSseOptions[0] as { authProvider?: Record<string, unknown> }).authProvider,
  932. ];
  933. for (const provider of providers) {
  934. expect(provider).toBeDefined();
  935. // 修复原因(根因 1):运行期只能是纯 AuthProvider。SDK 的 `isOAuthClientProvider()` 判定
  936. // 依赖 `clientInformation`/`tokens` 等方法是否存在;一旦被识别为 OAuthClientProvider,
  937. // transport 就会通过 `adaptOAuthProvider` 包裹它,401 走 SDK 的 `auth()`,绕过我们的
  938. // refresh 单飞锁,rotation 竞态立刻复发。同时它还会带来 discovery / DCR / callback listener。
  939. expect(typeof provider?.token).toBe("function");
  940. expect(typeof provider?.onUnauthorized).toBe("function");
  941. expect(provider?.clientInformation).toBeUndefined();
  942. expect(provider?.tokens).toBeUndefined();
  943. expect(provider?.saveTokens).toBeUndefined();
  944. expect(provider?.clientMetadata).toBeUndefined();
  945. expect(provider?.redirectToAuthorization).toBeUndefined();
  946. expect(provider?.saveCodeVerifier).toBeUndefined();
  947. }
  948. await adapter.close();
  949. });
  950. it("does not attach implicit OAuth provider when HTTP MCP has an Authorization header", async () => {
  951. const adapter = createMcpAdapter();
  952. await adapter.connectServer("manual-token", {
  953. type: "http",
  954. url: "https://mcp.example.test",
  955. headers: {
  956. Authorization: "Bearer user-token",
  957. },
  958. });
  959. expect((capturedHttpOptions[0] as { authProvider?: unknown }).authProvider).toBeUndefined();
  960. await adapter.close();
  961. });
  962. it("passes OAuth client credentials providers into HTTP and SSE MCP transports", async () => {
  963. const adapter = createMcpAdapter({
  964. clientName: "zcode-test",
  965. });
  966. await adapter.connectServer("http-demo", {
  967. type: "http",
  968. url: "https://mcp.example.test",
  969. headers: {
  970. "X-ZCode": "1",
  971. },
  972. oauth: {
  973. type: "client_credentials",
  974. clientId: "http-client",
  975. clientSecret: "http-secret",
  976. scope: "mcp:tools",
  977. },
  978. });
  979. await adapter.connectServer("sse-demo", {
  980. type: "sse",
  981. url: "https://mcp.example.test/sse",
  982. oauth: {
  983. type: "client_credentials",
  984. clientId: "sse-client",
  985. clientSecret: "sse-secret",
  986. },
  987. });
  988. const httpOptions = capturedHttpOptions[0] as {
  989. authProvider?: {
  990. clientInformation(): { client_id: string; client_secret?: string };
  991. clientMetadata: {
  992. client_name?: string;
  993. grant_types?: string[];
  994. scope?: string;
  995. };
  996. };
  997. requestInit?: { headers?: Record<string, string> };
  998. };
  999. const sseOptions = capturedSseOptions[0] as {
  1000. authProvider?: {
  1001. clientInformation(): { client_id: string; client_secret?: string };
  1002. clientMetadata: { client_name?: string; grant_types?: string[] };
  1003. };
  1004. };
  1005. expect(httpOptions.requestInit?.headers).toEqual({ "X-ZCode": "1" });
  1006. expect(httpOptions.authProvider?.clientInformation()).toEqual({
  1007. client_id: "http-client",
  1008. client_secret: "http-secret",
  1009. });
  1010. expect(httpOptions.authProvider?.clientMetadata).toMatchObject({
  1011. client_name: "zcode-test-http-demo",
  1012. grant_types: ["client_credentials"],
  1013. scope: "mcp:tools",
  1014. });
  1015. expect(sseOptions.authProvider?.clientInformation()).toEqual({
  1016. client_id: "sse-client",
  1017. client_secret: "sse-secret",
  1018. });
  1019. expect(sseOptions.authProvider?.clientMetadata).toMatchObject({
  1020. client_name: "zcode-test-sse-demo",
  1021. grant_types: ["client_credentials"],
  1022. });
  1023. });
  1024. it("exposes pending OAuth authorization URL through server status", async () => {
  1025. const { release: resolveConnect } = stubInteractiveAuthorization(
  1026. "https://auth.example.test/authorize?state=state_test",
  1027. );
  1028. const adapter = createMcpAdapter();
  1029. const connect = adapter.connectServer("notion", {
  1030. type: "http",
  1031. url: "https://mcp.example.test/mcp",
  1032. oauth: {
  1033. type: "authorization_code",
  1034. clientName: "ZCode",
  1035. },
  1036. });
  1037. let authorizationUrl: string | undefined;
  1038. for (let attempt = 0; attempt < 20; attempt += 1) {
  1039. const status = await adapter.status();
  1040. authorizationUrl = status.notion?.authorization?.authorizationUrl;
  1041. if (authorizationUrl) break;
  1042. await new Promise((resolve) => setTimeout(resolve, 10));
  1043. }
  1044. expect(authorizationUrl).toBe("https://auth.example.test/authorize?state=state_test");
  1045. resolveConnect();
  1046. await expect(connect).resolves.toMatchObject({
  1047. status: "connected",
  1048. toolCount: 0,
  1049. });
  1050. await adapter.close();
  1051. });
  1052. it("reuses an unchanged configured connection while OAuth authorization is pending", async () => {
  1053. const { release: resolveConnect } = stubInteractiveAuthorization(
  1054. "https://auth.example.test/authorize?state=stable_state",
  1055. );
  1056. const adapter = createMcpAdapter();
  1057. const firstConnect = adapter.connectConfiguredServers({
  1058. notion: {
  1059. type: "http",
  1060. url: "https://mcp.example.test/mcp",
  1061. oauth: {
  1062. type: "authorization_code",
  1063. clientName: "ZCode",
  1064. },
  1065. },
  1066. });
  1067. let authorizationUrl: string | undefined;
  1068. for (let attempt = 0; attempt < 20; attempt += 1) {
  1069. const status = await adapter.status();
  1070. authorizationUrl = status.notion?.authorization?.authorizationUrl;
  1071. if (authorizationUrl) break;
  1072. await new Promise((resolve) => setTimeout(resolve, 10));
  1073. }
  1074. const secondConnect = adapter.connectConfiguredServers({
  1075. notion: {
  1076. type: "http",
  1077. url: "https://mcp.example.test/mcp",
  1078. oauth: {
  1079. type: "authorization_code",
  1080. clientName: "ZCode",
  1081. },
  1082. },
  1083. });
  1084. await Promise.resolve();
  1085. expect(authorizationUrl).toBe("https://auth.example.test/authorize?state=stable_state");
  1086. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  1087. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  1088. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  1089. expect(capturedHttpOptions).toHaveLength(1);
  1090. await expect(adapter.status()).resolves.toMatchObject({
  1091. notion: {
  1092. authorization: {
  1093. authorizationUrl: "https://auth.example.test/authorize?state=stable_state",
  1094. },
  1095. status: "connecting",
  1096. },
  1097. });
  1098. resolveConnect();
  1099. await expect(Promise.all([firstConnect, secondConnect])).resolves.toMatchObject([
  1100. { statuses: { notion: { status: "connected" } } },
  1101. { statuses: { notion: { status: "connected" } } },
  1102. ]);
  1103. await adapter.close();
  1104. });
  1105. it("keeps a reused OAuth connection alive when a bounded caller times out", async () => {
  1106. const { release: resolveConnect } = stubInteractiveAuthorization(
  1107. "https://auth.example.test/authorize?state=shared_timeout_state",
  1108. );
  1109. const adapter = createMcpAdapter();
  1110. const servers = {
  1111. notion: {
  1112. type: "http" as const,
  1113. url: "https://mcp.example.test/mcp",
  1114. oauth: {
  1115. type: "authorization_code" as const,
  1116. clientName: "ZCode",
  1117. },
  1118. },
  1119. };
  1120. const settingsConnect = adapter.connectConfiguredServers(servers);
  1121. for (let attempt = 0; attempt < 20; attempt += 1) {
  1122. const status = await adapter.status();
  1123. if (status.notion?.authorization?.authorizationUrl) break;
  1124. await new Promise((resolve) => setTimeout(resolve, 10));
  1125. }
  1126. const sessionConnect = await adapter.connectConfiguredServers(servers, {
  1127. oauthAuthorizationTimeoutMs: 20,
  1128. });
  1129. expect(sessionConnect.statuses.notion).toMatchObject({
  1130. authorization: {
  1131. authorizationUrl: "https://auth.example.test/authorize?state=shared_timeout_state",
  1132. },
  1133. status: "connecting",
  1134. });
  1135. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  1136. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  1137. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  1138. expect(capturedHttpOptions).toHaveLength(1);
  1139. resolveConnect();
  1140. await expect(settingsConnect).resolves.toMatchObject({
  1141. statuses: { notion: { status: "connected" } },
  1142. });
  1143. await adapter.close();
  1144. });
  1145. it("only cancels the caller waiter when a reused OAuth connection is aborted", async () => {
  1146. const { release: resolveConnect } = stubInteractiveAuthorization(
  1147. "https://auth.example.test/authorize?state=shared_abort_state",
  1148. );
  1149. const adapter = createMcpAdapter();
  1150. const servers = {
  1151. notion: {
  1152. type: "http" as const,
  1153. url: "https://mcp.example.test/mcp",
  1154. oauth: {
  1155. type: "authorization_code" as const,
  1156. clientName: "ZCode",
  1157. },
  1158. },
  1159. };
  1160. const settingsConnect = adapter.connectConfiguredServers(servers);
  1161. for (let attempt = 0; attempt < 20; attempt += 1) {
  1162. const status = await adapter.status();
  1163. if (status.notion?.authorization?.authorizationUrl) break;
  1164. await new Promise((resolve) => setTimeout(resolve, 10));
  1165. }
  1166. const abortController = new AbortController();
  1167. const sessionConnect = adapter.connectConfiguredServers(servers, {
  1168. signal: abortController.signal,
  1169. });
  1170. abortController.abort(new Error("session stopped"));
  1171. await expect(sessionConnect).resolves.toMatchObject({
  1172. statuses: {
  1173. notion: {
  1174. authorization: {
  1175. authorizationUrl: "https://auth.example.test/authorize?state=shared_abort_state",
  1176. },
  1177. status: "connecting",
  1178. },
  1179. },
  1180. });
  1181. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  1182. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  1183. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  1184. expect(capturedHttpOptions).toHaveLength(1);
  1185. resolveConnect();
  1186. await expect(settingsConnect).resolves.toMatchObject({
  1187. statuses: { notion: { status: "connected" } },
  1188. });
  1189. await adapter.close();
  1190. });
  1191. it("treats per-connect OAuth authorization timeout as a caller budget, not a transaction kill", async () => {
  1192. let startAuthorization!: () => void;
  1193. const beforeAuthorization = new Promise<void>((resolve) => {
  1194. startAuthorization = resolve;
  1195. });
  1196. const { release, ready } = stubInteractiveAuthorization(
  1197. "https://auth.example.test/authorize?state=state_test",
  1198. beforeAuthorization,
  1199. );
  1200. const adapter = createMcpAdapter();
  1201. const startedAt = Date.now();
  1202. try {
  1203. const status = await adapter.connectServer(
  1204. "notion",
  1205. {
  1206. type: "http",
  1207. url: "https://mcp.example.test/mcp",
  1208. timeoutMs: 2_000,
  1209. oauth: { type: "authorization_code", clientName: "ZCode" },
  1210. },
  1211. { oauthAuthorizationTimeoutMs: 20 },
  1212. );
  1213. // URL 发布含异步存储,不能假定它比 20ms caller 预算更快;事务应在 caller 返回后继续。
  1214. expect(status).toMatchObject({ status: "connecting" });
  1215. expect(status.authorization).toBeUndefined();
  1216. expect(Date.now() - startedAt).toBeLessThan(1_000);
  1217. expect(transportFinishAuthMock).not.toHaveBeenCalled();
  1218. startAuthorization();
  1219. await ready;
  1220. await expect(adapter.status()).resolves.toMatchObject({
  1221. notion: {
  1222. authorization: {
  1223. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  1224. },
  1225. status: "connecting",
  1226. },
  1227. });
  1228. release();
  1229. await vi.waitFor(async () => {
  1230. expect(await adapter.status()).toMatchObject({ notion: { status: "connected" } });
  1231. });
  1232. } finally {
  1233. startAuthorization();
  1234. release();
  1235. await adapter.close();
  1236. }
  1237. });
  1238. it("keeps runtime OAuth recovery alive after the triggering caller times out", async () => {
  1239. let startAuthorization!: () => void;
  1240. const beforeAuthorization = new Promise<void>((resolve) => {
  1241. startAuthorization = resolve;
  1242. });
  1243. let markReady!: () => void;
  1244. const ready = new Promise<void>((resolve) => {
  1245. markReady = resolve;
  1246. });
  1247. let releaseAuthorization!: () => void;
  1248. const authorizationGate = new Promise<void>((resolve) => {
  1249. releaseAuthorization = resolve;
  1250. });
  1251. authMock.mockImplementation(async (provider: unknown) => {
  1252. const interactiveProvider = provider as {
  1253. redirectToAuthorization(url: URL): Promise<void>;
  1254. state(): Promise<string>;
  1255. };
  1256. const authorizationUrl = new URL("https://auth.example.test/authorize");
  1257. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  1258. await beforeAuthorization;
  1259. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  1260. markReady();
  1261. await authorizationGate;
  1262. return "AUTHORIZED" as const;
  1263. });
  1264. clientCallToolMock
  1265. .mockRejectedValueOnce(new UnauthorizedError())
  1266. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  1267. const adapter = createMcpAdapter();
  1268. await adapter.connectServer("runtime", {
  1269. oauth: {
  1270. type: "authorization_code",
  1271. },
  1272. type: "http",
  1273. url: "https://mcp.example.test/mcp",
  1274. });
  1275. const call = adapter.callTool(
  1276. {
  1277. serverName: "runtime",
  1278. toolName: "oauth_ping",
  1279. },
  1280. { timeoutMs: 20 },
  1281. );
  1282. try {
  1283. await expect(observePromiseWithin(call, 200)).resolves.toMatchObject({
  1284. reason: {
  1285. name: "McpTimeoutError",
  1286. },
  1287. status: "rejected",
  1288. });
  1289. // 显式让 caller 先超时,再发布 URL,避免靠机器负载决定断言先后。
  1290. startAuthorization();
  1291. await ready;
  1292. await expect(adapter.status()).resolves.toMatchObject({
  1293. runtime: {
  1294. authorization: {
  1295. authorizationUrl: expect.stringContaining("https://auth.example.test/authorize"),
  1296. },
  1297. status: "connecting",
  1298. },
  1299. });
  1300. releaseAuthorization();
  1301. for (let attempt = 0; attempt < 50; attempt += 1) {
  1302. const status = await adapter.status();
  1303. if (status.runtime?.status === "connected") break;
  1304. await new Promise((resolve) => setTimeout(resolve, 10));
  1305. }
  1306. await expect(adapter.status()).resolves.toMatchObject({
  1307. runtime: { status: "connected" },
  1308. });
  1309. await expect(
  1310. adapter.callTool(
  1311. {
  1312. serverName: "runtime",
  1313. toolName: "oauth_ping",
  1314. },
  1315. { timeoutMs: 200 },
  1316. ),
  1317. ).resolves.toMatchObject({
  1318. content: [{ text: "ok", type: "text" }],
  1319. });
  1320. expect(authMock).toHaveBeenCalledTimes(1);
  1321. // 原 caller 已经超时,后台 recovery 只负责重连;不会替超时 caller 再执行工具。
  1322. expect(clientCallToolMock).toHaveBeenCalledTimes(2);
  1323. } finally {
  1324. startAuthorization();
  1325. releaseAuthorization();
  1326. await Promise.allSettled([call]);
  1327. await adapter.close();
  1328. }
  1329. });
  1330. it("shares one runtime OAuth recovery across concurrent tool callers", async () => {
  1331. let releaseAuthorization!: () => void;
  1332. const authorizationGate = new Promise<void>((resolve) => {
  1333. releaseAuthorization = resolve;
  1334. });
  1335. authMock.mockImplementation(async (provider: unknown) => {
  1336. const interactiveProvider = provider as {
  1337. redirectToAuthorization(url: URL): Promise<void>;
  1338. state(): Promise<string>;
  1339. };
  1340. const authorizationUrl = new URL("https://auth.example.test/authorize");
  1341. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  1342. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  1343. await authorizationGate;
  1344. return "AUTHORIZED" as const;
  1345. });
  1346. clientCallToolMock
  1347. .mockRejectedValueOnce(new UnauthorizedError())
  1348. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  1349. const adapter = createMcpAdapter();
  1350. await adapter.connectServer("runtime", {
  1351. oauth: {
  1352. type: "authorization_code",
  1353. },
  1354. type: "http",
  1355. url: "https://mcp.example.test/mcp",
  1356. });
  1357. const firstCall = adapter.callTool(
  1358. {
  1359. serverName: "runtime",
  1360. toolName: "oauth_ping",
  1361. },
  1362. { timeoutMs: 2_000 },
  1363. );
  1364. try {
  1365. for (let attempt = 0; attempt < 50; attempt += 1) {
  1366. const status = await adapter.status();
  1367. if (status.runtime?.authorization?.authorizationUrl) break;
  1368. await new Promise((resolve) => setTimeout(resolve, 10));
  1369. }
  1370. await expect(adapter.status()).resolves.toMatchObject({
  1371. runtime: {
  1372. authorization: {
  1373. authorizationUrl: expect.stringContaining("https://auth.example.test/authorize"),
  1374. },
  1375. status: "connecting",
  1376. },
  1377. });
  1378. const secondCall = adapter.callTool(
  1379. {
  1380. serverName: "runtime",
  1381. toolName: "oauth_ping",
  1382. },
  1383. { timeoutMs: 2_000 },
  1384. );
  1385. await Promise.resolve();
  1386. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  1387. releaseAuthorization();
  1388. await expect(Promise.all([firstCall, secondCall])).resolves.toMatchObject([
  1389. { content: [{ text: "ok", type: "text" }] },
  1390. { content: [{ text: "ok", type: "text" }] },
  1391. ]);
  1392. expect(authMock).toHaveBeenCalledTimes(1);
  1393. // 第一次认证失败 + first caller 的一次安全重试 + second caller 的首次实际调用。
  1394. expect(clientCallToolMock).toHaveBeenCalledTimes(3);
  1395. await expect(adapter.status()).resolves.toMatchObject({
  1396. runtime: { status: "connected" },
  1397. });
  1398. } finally {
  1399. releaseAuthorization();
  1400. await Promise.allSettled([firstCall]);
  1401. await adapter.close();
  1402. }
  1403. });
  1404. it("does not let a caller abort close the shared runtime OAuth callback listener", async () => {
  1405. let authorizationContext:
  1406. | {
  1407. authorizationUrl: string;
  1408. redirectUrl: string;
  1409. }
  1410. | undefined;
  1411. authMock.mockImplementation(
  1412. async (provider: unknown, options?: { authorizationCode?: string }) => {
  1413. if (options?.authorizationCode) return "AUTHORIZED" as const;
  1414. const interactiveProvider = provider as {
  1415. redirectToAuthorization(url: URL): Promise<void>;
  1416. state(): Promise<string>;
  1417. };
  1418. const authorizationUrl = new URL("https://auth.example.test/authorize");
  1419. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  1420. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  1421. return "REDIRECT" as never;
  1422. },
  1423. );
  1424. clientCallToolMock
  1425. .mockRejectedValueOnce(new UnauthorizedError())
  1426. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  1427. const adapter = createMcpAdapter({
  1428. mcpOAuth: {
  1429. onAuthorizationRequired: async (context) => {
  1430. authorizationContext = context;
  1431. },
  1432. },
  1433. });
  1434. await adapter.connectServer("runtime", {
  1435. oauth: {
  1436. type: "authorization_code",
  1437. },
  1438. type: "http",
  1439. url: "https://mcp.example.test/mcp",
  1440. });
  1441. const abortController = new AbortController();
  1442. const call = adapter.callTool(
  1443. {
  1444. serverName: "runtime",
  1445. toolName: "oauth_ping",
  1446. },
  1447. {
  1448. signal: abortController.signal,
  1449. timeoutMs: 2_000,
  1450. },
  1451. );
  1452. try {
  1453. for (let attempt = 0; attempt < 50; attempt += 1) {
  1454. if (authorizationContext) break;
  1455. await new Promise((resolve) => setTimeout(resolve, 10));
  1456. }
  1457. expect(authorizationContext).toBeDefined();
  1458. abortController.abort(new Error("caller stopped"));
  1459. await expect(observePromiseWithin(call, 200)).resolves.toMatchObject({
  1460. reason: {
  1461. message: "caller stopped",
  1462. },
  1463. status: "rejected",
  1464. });
  1465. const callbackUrl = new URL(authorizationContext!.redirectUrl);
  1466. callbackUrl.searchParams.set("code", "authorized-after-caller-abort");
  1467. callbackUrl.searchParams.set(
  1468. "state",
  1469. new URL(authorizationContext!.authorizationUrl).searchParams.get("state") ?? "",
  1470. );
  1471. await expect(fetch(callbackUrl)).resolves.toMatchObject({ ok: true });
  1472. for (let attempt = 0; attempt < 50; attempt += 1) {
  1473. const status = await adapter.status();
  1474. if (status.runtime?.status === "connected") break;
  1475. await new Promise((resolve) => setTimeout(resolve, 10));
  1476. }
  1477. await expect(adapter.status()).resolves.toMatchObject({
  1478. runtime: { status: "connected" },
  1479. });
  1480. expect(authMock).toHaveBeenCalledTimes(2);
  1481. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  1482. } finally {
  1483. await Promise.allSettled([call]);
  1484. await adapter.close();
  1485. }
  1486. });
  1487. it("converges Phase 2 orchestration errors to a retryable failed server status", async () => {
  1488. const credentialError = new Error("Unable to read shared ZCode credentials");
  1489. const credentialStore = {
  1490. filePath: "/tmp/zcode-unreadable-credentials.json",
  1491. load: vi.fn(async () => {
  1492. throw credentialError;
  1493. }),
  1494. loadMany: vi.fn(async () => {
  1495. throw credentialError;
  1496. }),
  1497. } as unknown as SharedZCodeCredentialStore;
  1498. clientConnectMock.mockRejectedValue(new UnauthorizedError());
  1499. const adapter = createMcpAdapter({
  1500. mcpOAuth: {
  1501. credentialStore,
  1502. },
  1503. });
  1504. const config = {
  1505. oauth: {
  1506. type: "authorization_code" as const,
  1507. },
  1508. type: "http" as const,
  1509. url: "https://mcp.example.test/mcp",
  1510. };
  1511. try {
  1512. await expect(adapter.connectConfiguredServers({ broken: config })).resolves.toMatchObject({
  1513. statuses: {
  1514. broken: {
  1515. error: "Unable to read shared ZCode credentials",
  1516. failureKind: "oauth_authorization_failed",
  1517. status: "failed",
  1518. },
  1519. },
  1520. });
  1521. await expect(adapter.status()).resolves.toMatchObject({
  1522. broken: {
  1523. failureKind: "oauth_authorization_failed",
  1524. status: "failed",
  1525. },
  1526. });
  1527. await expect(adapter.connectConfiguredServers({ broken: config })).resolves.toMatchObject({
  1528. statuses: {
  1529. broken: {
  1530. failureKind: "oauth_authorization_failed",
  1531. status: "failed",
  1532. },
  1533. },
  1534. });
  1535. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  1536. } finally {
  1537. await adapter.close();
  1538. }
  1539. });
  1540. it("only opens OAuth authorization URL when an opener is injected", async () => {
  1541. const openAuthorizationUrl = vi.fn(async () => {});
  1542. const { release: resolveConnect } = stubInteractiveAuthorization(
  1543. "https://auth.example.test/authorize?state=state_test",
  1544. );
  1545. const adapter = createMcpAdapter({
  1546. mcpOAuth: {
  1547. openAuthorizationUrl,
  1548. },
  1549. });
  1550. const connect = adapter.connectServer("notion", {
  1551. type: "http",
  1552. url: "https://mcp.example.test/mcp",
  1553. oauth: {
  1554. type: "authorization_code",
  1555. clientName: "ZCode",
  1556. },
  1557. });
  1558. for (let attempt = 0; attempt < 20; attempt += 1) {
  1559. const status = await adapter.status();
  1560. if (status.notion?.authorization?.authorizationUrl) break;
  1561. await new Promise((resolve) => setTimeout(resolve, 10));
  1562. }
  1563. expect(openAuthorizationUrl).toHaveBeenCalledWith(
  1564. expect.objectContaining({
  1565. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  1566. serverName: "notion",
  1567. }),
  1568. );
  1569. resolveConnect();
  1570. await expect(connect).resolves.toMatchObject({
  1571. status: "connected",
  1572. toolCount: 0,
  1573. });
  1574. await adapter.close();
  1575. });
  1576. });