mcp.test.ts 53 KB

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