mcp.test.ts 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  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: expect.stringContaining("fatal: database refused connection"),
  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. const status = (await adapter.status())["mysql-local"];
  624. expect(status?.error).toContain("MCP error -32000: Connection closed");
  625. expect(status?.error).toContain("MYSQL_PASS=[Redacted]");
  626. expect(status?.error).not.toContain("super-secret");
  627. expect(status?.error).not.toContain("live-token");
  628. await adapter.close();
  629. });
  630. it.each([
  631. ["python", "ModuleNotFoundError: No module named 'mcp'"],
  632. ["node", "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'example-mcp'"],
  633. ["path", "ENOENT: no such file or directory"],
  634. ["permission", "PermissionError: [Errno 13] Permission denied"],
  635. ])(
  636. "exposes bounded sanitized %s startup evidence without changing failure kind",
  637. async (_name, cause) => {
  638. clientConnectMock.mockImplementation(async () => {
  639. capturedStdioStderrHandlers[0]?.(
  640. Buffer.from(
  641. "noise".repeat(1_000) +
  642. "\n\u001b[31m" +
  643. cause +
  644. "\u001b[0m\nAPI_TOKEN=fixture-secret\n",
  645. ),
  646. );
  647. throw new Error("Connection closed");
  648. });
  649. const adapter = createMcpAdapter();
  650. try {
  651. const status = await adapter.connectServer("broken", { command: "node", type: "stdio" });
  652. expect(status).toMatchObject({ status: "failed", failureKind: "process_start_failed" });
  653. expect(status.error).toContain(cause);
  654. expect(status.error).toContain("Connection closed");
  655. expect(status.error).not.toContain("\u001b");
  656. expect(status.error).not.toContain("fixture-secret");
  657. expect(status.error!.length).toBeLessThanOrEqual(4_520);
  658. } finally {
  659. await adapter.close();
  660. }
  661. },
  662. );
  663. it("keeps HTTP failures separate from recent stdio stderr", async () => {
  664. clientConnectMock.mockRejectedValue(new Error("network unavailable"));
  665. const adapter = createMcpAdapter();
  666. try {
  667. const status = await adapter.connectServer("http-failure", {
  668. type: "http",
  669. url: "https://example.com/mcp",
  670. headers: { Authorization: "Bearer fixture" },
  671. });
  672. expect(status.error).toBe("network unavailable");
  673. expect(status.failureKind).toBe("network_unreachable");
  674. } finally {
  675. await adapter.close();
  676. }
  677. });
  678. it("redacts quoted and escaped credential values before exposing stderr", async () => {
  679. clientConnectMock.mockImplementation(async () => {
  680. capturedStdioStderrHandlers[0]?.(
  681. Buffer.from(
  682. [
  683. 'API_TOKEN="first secret with spaces"',
  684. String.raw`VE_SPEECH_MCP_TOKEN="second escaped\" secret"`,
  685. String.raw`{"access_token":"third escaped\" secret"}`,
  686. "ModuleNotFoundError: No module named 'mcp'",
  687. ].join("\n"),
  688. ),
  689. );
  690. throw new Error("Connection closed");
  691. });
  692. const adapter = createMcpAdapter();
  693. try {
  694. const status = await adapter.connectServer("quoted-secret", {
  695. command: "node",
  696. type: "stdio",
  697. });
  698. expect(status.error).toContain("No module named 'mcp'");
  699. expect(status.error).not.toContain("secret");
  700. expect(status.error).not.toContain("escaped");
  701. expect(status.error).not.toContain("spaces");
  702. } finally {
  703. await adapter.close();
  704. }
  705. });
  706. it("does not leak a credential whose key name is cut by stderr tail truncation", async () => {
  707. clientConnectMock.mockImplementation(async () => {
  708. // 构造保留的 4000 字符尾部恰好从键名 VE_SPEECH_MCP_TOKEN 中间的 KEN 开始。
  709. const head = "KEN=fixture-secret\nreal failure\n";
  710. const tail = `${head}${"y".repeat(4000 - head.length - 1)}\n`;
  711. capturedStdioStderrHandlers[0]?.(Buffer.from(`first line\nVE_SPEECH_MCP_TO${tail}`));
  712. throw new Error("Connection closed");
  713. });
  714. const adapter = createMcpAdapter();
  715. try {
  716. const status = await adapter.connectServer("cut-key", { command: "node", type: "stdio" });
  717. expect(status.error).toContain("real failure");
  718. expect(status.error).not.toContain("fixture-secret");
  719. } finally {
  720. await adapter.close();
  721. }
  722. });
  723. it("keeps stderr after a CR-only boundary when tail truncation cuts a credential key", async () => {
  724. clientConnectMock.mockImplementation(async () => {
  725. const tail = `KEN=fixture-secret\rreal failure\r${"y".repeat(4100)}\rreal failure`;
  726. capturedStdioStderrHandlers[0]?.(Buffer.from(`VE_SPEECH_MCP_TO${tail}`));
  727. throw new Error("Connection closed");
  728. });
  729. const adapter = createMcpAdapter();
  730. try {
  731. const status = await adapter.connectServer("cr-only", { command: "node", type: "stdio" });
  732. expect(status.error).toContain("real failure");
  733. expect(status.error).not.toContain("fixture-secret");
  734. } finally {
  735. await adapter.close();
  736. }
  737. });
  738. it.each([" ", ",", ";", "&"])(
  739. "fails closed when tail truncation cuts a quoted credential containing %j and no newline remains",
  740. async (separator) => {
  741. const warnMock = vi.fn();
  742. const logger = {
  743. child: vi.fn(),
  744. debug: vi.fn(),
  745. error: vi.fn(),
  746. info: vi.fn(),
  747. warn: warnMock,
  748. };
  749. logger.child.mockReturnValue(logger);
  750. clientConnectMock.mockImplementation(async () => {
  751. // 保留的 4000 字符尾部从 KEN="..." 开始且没有换行,凭证值内含分隔符。
  752. const tail = `KEN="fixture${separator}leaked-suffix"`;
  753. // 前缀 16 字符 + 4000 字符,保留的尾部正好从 KEN 开始。
  754. const input = `VE_SPEECH_MCP_TO${tail}${"y".repeat(4000 - tail.length)}`;
  755. capturedStdioStderrHandlers[0]?.(Buffer.from(input));
  756. throw new Error("Connection closed");
  757. });
  758. const adapter = createMcpAdapter({ logger });
  759. try {
  760. const status = await adapter.connectServer("long-line", { command: "node", type: "stdio" });
  761. expect(status.error).toContain("Connection closed");
  762. for (const text of [status.error, JSON.stringify(warnMock.mock.calls)]) {
  763. expect(text).not.toContain("fixture");
  764. expect(text).not.toContain("leaked-suffix");
  765. }
  766. } finally {
  767. await adapter.close();
  768. }
  769. },
  770. );
  771. it("marks the record disconnected and logs recent stderr when the transport closes unexpectedly", async () => {
  772. const warnMock = vi.fn();
  773. const logger = {
  774. child: vi.fn(),
  775. debug: vi.fn(),
  776. error: vi.fn(),
  777. info: vi.fn(),
  778. warn: warnMock,
  779. };
  780. logger.child.mockReturnValue(logger);
  781. const telemetryEvents: Array<{ kind: string; mcpInstanceId?: string }> = [];
  782. const telemetry = createMcpTelemetryTracker({
  783. idSalt: "device-a",
  784. onEvent: (event) => telemetryEvents.push(event),
  785. randomId: () => "mcp-instance-1",
  786. });
  787. telemetry.registerConnection({
  788. connectionId: "connection-1",
  789. isolation: "session",
  790. serverName: "node_repl",
  791. });
  792. telemetry.acquireOwner({
  793. connectionId: "connection-1",
  794. ownerId: "lease-1",
  795. sessionId: "session-1",
  796. });
  797. const adapter = createMcpAdapter({
  798. connectionContext: {
  799. mcpConnectionId: "connection-1",
  800. mcpIsolation: "session",
  801. sessionId: "session-1",
  802. },
  803. logger,
  804. telemetry,
  805. });
  806. await adapter.connectServer("node_repl", {
  807. command: "node",
  808. type: "stdio",
  809. });
  810. capturedStdioStderrHandlers[0]?.(
  811. Buffer.from("node_repl uncaughtException: boom from async timer\n"),
  812. );
  813. capturedClients.at(-1)?.onclose?.();
  814. expect(warnMock).toHaveBeenCalledWith(
  815. "MCP server connection lost",
  816. expect.objectContaining({
  817. event: "mcp.server.connection_lost",
  818. mcpServerName: "node_repl",
  819. mcpTransportPid: 42_424,
  820. stderr: expect.stringContaining("boom from async timer"),
  821. }),
  822. );
  823. const statuses = await adapter.status();
  824. expect(statuses.node_repl?.status).toBe("disconnected");
  825. expect(statuses.node_repl?.failureKind).toBe("unexpected_disconnect");
  826. expect(telemetryEvents.map((event) => [event.kind, event.mcpInstanceId])).toEqual([
  827. ["process_start", "mcp-instance-1"],
  828. ["process_crash", "mcp-instance-1"],
  829. ]);
  830. });
  831. it("does not report connection_lost when the server is closed deliberately", async () => {
  832. const warnMock = vi.fn();
  833. const logger = {
  834. child: vi.fn(),
  835. debug: vi.fn(),
  836. error: vi.fn(),
  837. info: vi.fn(),
  838. warn: warnMock,
  839. };
  840. logger.child.mockReturnValue(logger);
  841. const adapter = createMcpAdapter({ logger });
  842. await adapter.connectServer("node_repl", {
  843. command: "node",
  844. type: "stdio",
  845. });
  846. await adapter.disconnectServer("node_repl");
  847. capturedClients.at(-1)?.onclose?.();
  848. expect(warnMock).not.toHaveBeenCalledWith("MCP server connection lost", expect.anything());
  849. });
  850. // Bugfix 回归:HTTP/SSE MCP 被停掉不会派发 onclose,status() 会一直停在 connected。
  851. // 设置页刷新依赖 pingServer 把这种无声死亡暴露出来。
  852. it("keeps the server connected when the ping succeeds", async () => {
  853. const adapter = createMcpAdapter();
  854. await adapter.connectServer("official_tools", {
  855. type: "http",
  856. url: "https://mcp.example/mcp",
  857. });
  858. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(true);
  859. expect((await adapter.status()).official_tools?.status).toBe("connected");
  860. });
  861. it("marks the server disconnected when the ping hits a dead transport", async () => {
  862. const warnMock = vi.fn();
  863. const logger = {
  864. child: vi.fn(),
  865. debug: vi.fn(),
  866. error: vi.fn(),
  867. info: vi.fn(),
  868. warn: warnMock,
  869. };
  870. logger.child.mockReturnValue(logger);
  871. const adapter = createMcpAdapter({ logger });
  872. await adapter.connectServer("official_tools", {
  873. type: "http",
  874. url: "https://mcp.example/mcp",
  875. });
  876. // SDK 本地错误用字符串 code(REQUEST_TIMEOUT / CONNECTION_CLOSED …)。
  877. clientPingMock.mockRejectedValue(
  878. Object.assign(new Error("Request timed out"), { code: "REQUEST_TIMEOUT" }),
  879. );
  880. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(false);
  881. expect((await adapter.status()).official_tools).toMatchObject({
  882. failureKind: "unexpected_disconnect",
  883. status: "disconnected",
  884. });
  885. expect(warnMock).toHaveBeenCalledWith(
  886. "MCP server ping failed",
  887. expect.objectContaining({
  888. event: "mcp.server.ping.failed",
  889. mcpServerName: "official_tools",
  890. }),
  891. );
  892. });
  893. it("treats a JSON-RPC error answer as a live connection", async () => {
  894. const adapter = createMcpAdapter();
  895. await adapter.connectServer("official_tools", {
  896. type: "http",
  897. url: "https://mcp.example/mcp",
  898. });
  899. // server 回了 method-not-found:请求走通了,连接是活的,不能据此拆连接。
  900. clientPingMock.mockRejectedValue(
  901. Object.assign(new Error("Method not found"), { code: -32_601 }),
  902. );
  903. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(true);
  904. expect((await adapter.status()).official_tools?.status).toBe("connected");
  905. });
  906. it("reports an unknown server as not alive", async () => {
  907. const adapter = createMcpAdapter();
  908. await expect(adapter.pingServer?.("missing")).resolves.toBe(false);
  909. });
  910. it("reconnects and retries once when the tool call hits a dead transport", async () => {
  911. const adapter = createMcpAdapter();
  912. await adapter.connectServer("node_repl", {
  913. command: "node",
  914. type: "stdio",
  915. });
  916. clientCallToolMock
  917. .mockRejectedValueOnce(new Error("Not connected"))
  918. .mockResolvedValueOnce({ content: [{ type: "text", text: "revived" }] });
  919. const result = await adapter.callTool({
  920. arguments: { code: "1 + 1" },
  921. serverName: "node_repl",
  922. toolName: "js",
  923. });
  924. expect(result.content).toEqual([{ type: "text", text: "revived" }]);
  925. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  926. expect(clientCallToolMock).toHaveBeenCalledTimes(2);
  927. });
  928. it("reconnects before calling when the record was already marked disconnected", async () => {
  929. const adapter = createMcpAdapter();
  930. await adapter.connectServer("node_repl", {
  931. command: "node",
  932. type: "stdio",
  933. });
  934. capturedClients.at(-1)?.onclose?.();
  935. expect((await adapter.status()).node_repl?.status).toBe("disconnected");
  936. const result = await adapter.callTool({
  937. arguments: { code: "1 + 1" },
  938. serverName: "node_repl",
  939. toolName: "js",
  940. });
  941. expect(result.content).toEqual([{ type: "text", text: "ok" }]);
  942. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  943. expect((await adapter.status()).node_repl?.status).toBe("connected");
  944. });
  945. it("surfaces the original error when reconnection also fails", async () => {
  946. const adapter = createMcpAdapter();
  947. await adapter.connectServer("node_repl", {
  948. command: "node",
  949. type: "stdio",
  950. });
  951. clientCallToolMock.mockRejectedValue(new Error("Not connected"));
  952. clientConnectMock.mockRejectedValue(new Error("spawn ENOENT"));
  953. await expect(
  954. adapter.callTool({
  955. arguments: { code: "1 + 1" },
  956. serverName: "node_repl",
  957. toolName: "js",
  958. }),
  959. ).rejects.toThrow(/Not connected/);
  960. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  961. });
  962. it("injects unified network env into stdio MCP transports", async () => {
  963. const adapter = createMcpAdapter({
  964. env: {
  965. PATH: dirname(process.execPath),
  966. ZCODE_AGENT_CA_CERT: "/tmp/root-ca.pem",
  967. },
  968. network: {
  969. httpProxy: "127.0.0.1:8888",
  970. noProxy: "localhost,127.0.0.1",
  971. },
  972. });
  973. await adapter.connectServer("demo", {
  974. command: "node",
  975. env: {
  976. MCP_TOKEN: "secret",
  977. },
  978. type: "stdio",
  979. });
  980. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  981. expect(options.env).toMatchObject({
  982. ALL_PROXY: "http://127.0.0.1:8888",
  983. CURL_CA_BUNDLE: "/tmp/root-ca.pem",
  984. GIT_SSL_CAINFO: "/tmp/root-ca.pem",
  985. HTTPS_PROXY: "http://127.0.0.1:8888",
  986. HTTP_PROXY: "http://127.0.0.1:8888",
  987. MCP_TOKEN: "secret",
  988. NODE_EXTRA_CA_CERTS: "/tmp/root-ca.pem",
  989. NO_PROXY: "localhost,127.0.0.1",
  990. // MCP 会补齐 Node 目录;本测试使用已含 Node 的 PATH,避免依赖测试机的 /bin。
  991. PATH: dirname(process.execPath),
  992. REQUESTS_CA_BUNDLE: "/tmp/root-ca.pem",
  993. SSL_CERT_FILE: "/tmp/root-ca.pem",
  994. all_proxy: "http://127.0.0.1:8888",
  995. http_proxy: "http://127.0.0.1:8888",
  996. https_proxy: "http://127.0.0.1:8888",
  997. no_proxy: "localhost,127.0.0.1",
  998. });
  999. });
  1000. it("appends the injected node fallback after the server env", async () => {
  1001. const resolve = vi.fn(async () => ({
  1002. binDir: "/fallback/bin",
  1003. env: { ZCODE_NODE_FALLBACK_EXEC_PATH: "/electron" },
  1004. }));
  1005. const adapter = createMcpAdapter({
  1006. env: { PATH: dirname(process.execPath) },
  1007. nodeFallback: { resolve },
  1008. });
  1009. await adapter.connectServer("demo", {
  1010. command: "node",
  1011. // 插件自带 PATH 会整体替换宿主 PATH;fallback 仍须追加在它后面。
  1012. env: { PATH: "/plugin/bin" },
  1013. type: "stdio",
  1014. });
  1015. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  1016. expect(options.env?.PATH).toBe(["/plugin/bin", "/fallback/bin"].join(delimiter));
  1017. expect(options.env?.ZCODE_NODE_FALLBACK_EXEC_PATH).toBe("/electron");
  1018. expect(resolve).toHaveBeenCalledTimes(1);
  1019. });
  1020. it("restores captured user network env into stdio MCP transports", async () => {
  1021. const adapter = createMcpAdapter({
  1022. env: {
  1023. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  1024. NODE_EXTRA_CA_CERTS: "/tmp/user-ca.pem",
  1025. http_proxy: "http://user-proxy:8080",
  1026. }),
  1027. PATH: dirname(process.execPath),
  1028. },
  1029. network: {},
  1030. });
  1031. await adapter.connectServer("demo", {
  1032. command: "node",
  1033. type: "stdio",
  1034. });
  1035. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  1036. expect(options.env).toMatchObject({
  1037. NODE_EXTRA_CA_CERTS: "/tmp/user-ca.pem",
  1038. PATH: dirname(process.execPath),
  1039. http_proxy: "http://user-proxy:8080",
  1040. });
  1041. expect(options.env?.[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
  1042. });
  1043. it("passes proxy-aware fetch into HTTP and SSE MCP transports", async () => {
  1044. const adapter = createMcpAdapter({
  1045. env: {
  1046. ZCODE_HTTP_PROXY: "http://127.0.0.1:8888",
  1047. },
  1048. network: {},
  1049. });
  1050. await adapter.connectServer("http-demo", {
  1051. type: "http",
  1052. url: "https://mcp.example.test",
  1053. });
  1054. await adapter.connectServer("sse-demo", {
  1055. type: "sse",
  1056. url: "https://mcp.example.test/sse",
  1057. });
  1058. expect(capturedHttpOptions[0]).toMatchObject({
  1059. fetch: expect.any(Function),
  1060. });
  1061. expect(capturedSseOptions[0]).toMatchObject({
  1062. fetch: expect.any(Function),
  1063. });
  1064. await adapter.close();
  1065. });
  1066. it("passes a pure token AuthProvider into bare HTTP and SSE MCP transports", async () => {
  1067. const adapter = createMcpAdapter();
  1068. await adapter.connectServer("http-demo", {
  1069. type: "http",
  1070. url: "https://mcp.example.test",
  1071. });
  1072. await adapter.connectServer("sse-demo", {
  1073. type: "sse",
  1074. url: "https://mcp.example.test/sse",
  1075. });
  1076. const providers = [
  1077. (capturedHttpOptions[0] as { authProvider?: Record<string, unknown> }).authProvider,
  1078. (capturedSseOptions[0] as { authProvider?: Record<string, unknown> }).authProvider,
  1079. ];
  1080. for (const provider of providers) {
  1081. expect(provider).toBeDefined();
  1082. // 修复原因(根因 1):运行期只能是纯 AuthProvider。SDK 的 `isOAuthClientProvider()` 判定
  1083. // 依赖 `clientInformation`/`tokens` 等方法是否存在;一旦被识别为 OAuthClientProvider,
  1084. // transport 就会通过 `adaptOAuthProvider` 包裹它,401 走 SDK 的 `auth()`,绕过我们的
  1085. // refresh 单飞锁,rotation 竞态立刻复发。同时它还会带来 discovery / DCR / callback listener。
  1086. expect(typeof provider?.token).toBe("function");
  1087. expect(typeof provider?.onUnauthorized).toBe("function");
  1088. expect(provider?.clientInformation).toBeUndefined();
  1089. expect(provider?.tokens).toBeUndefined();
  1090. expect(provider?.saveTokens).toBeUndefined();
  1091. expect(provider?.clientMetadata).toBeUndefined();
  1092. expect(provider?.redirectToAuthorization).toBeUndefined();
  1093. expect(provider?.saveCodeVerifier).toBeUndefined();
  1094. }
  1095. await adapter.close();
  1096. });
  1097. it("does not attach implicit OAuth provider when HTTP MCP has an Authorization header", async () => {
  1098. const adapter = createMcpAdapter();
  1099. await adapter.connectServer("manual-token", {
  1100. type: "http",
  1101. url: "https://mcp.example.test",
  1102. headers: {
  1103. Authorization: "Bearer user-token",
  1104. },
  1105. });
  1106. expect((capturedHttpOptions[0] as { authProvider?: unknown }).authProvider).toBeUndefined();
  1107. await adapter.close();
  1108. });
  1109. it("passes OAuth client credentials providers into HTTP and SSE MCP transports", async () => {
  1110. const adapter = createMcpAdapter({
  1111. clientName: "zcode-test",
  1112. });
  1113. await adapter.connectServer("http-demo", {
  1114. type: "http",
  1115. url: "https://mcp.example.test",
  1116. headers: {
  1117. "X-ZCode": "1",
  1118. },
  1119. oauth: {
  1120. type: "client_credentials",
  1121. clientId: "http-client",
  1122. clientSecret: "http-secret",
  1123. scope: "mcp:tools",
  1124. },
  1125. });
  1126. await adapter.connectServer("sse-demo", {
  1127. type: "sse",
  1128. url: "https://mcp.example.test/sse",
  1129. oauth: {
  1130. type: "client_credentials",
  1131. clientId: "sse-client",
  1132. clientSecret: "sse-secret",
  1133. },
  1134. });
  1135. const httpOptions = capturedHttpOptions[0] as {
  1136. authProvider?: {
  1137. clientInformation(): { client_id: string; client_secret?: string };
  1138. clientMetadata: {
  1139. client_name?: string;
  1140. grant_types?: string[];
  1141. scope?: string;
  1142. };
  1143. };
  1144. requestInit?: { headers?: Record<string, string> };
  1145. };
  1146. const sseOptions = capturedSseOptions[0] as {
  1147. authProvider?: {
  1148. clientInformation(): { client_id: string; client_secret?: string };
  1149. clientMetadata: { client_name?: string; grant_types?: string[] };
  1150. };
  1151. };
  1152. expect(httpOptions.requestInit?.headers).toEqual({ "X-ZCode": "1" });
  1153. expect(httpOptions.authProvider?.clientInformation()).toEqual({
  1154. client_id: "http-client",
  1155. client_secret: "http-secret",
  1156. });
  1157. expect(httpOptions.authProvider?.clientMetadata).toMatchObject({
  1158. client_name: "zcode-test-http-demo",
  1159. grant_types: ["client_credentials"],
  1160. scope: "mcp:tools",
  1161. });
  1162. expect(sseOptions.authProvider?.clientInformation()).toEqual({
  1163. client_id: "sse-client",
  1164. client_secret: "sse-secret",
  1165. });
  1166. expect(sseOptions.authProvider?.clientMetadata).toMatchObject({
  1167. client_name: "zcode-test-sse-demo",
  1168. grant_types: ["client_credentials"],
  1169. });
  1170. });
  1171. it("exposes pending OAuth authorization URL through server status", async () => {
  1172. const { release: resolveConnect } = stubInteractiveAuthorization(
  1173. "https://auth.example.test/authorize?state=state_test",
  1174. );
  1175. const adapter = createMcpAdapter();
  1176. const connect = adapter.connectServer("notion", {
  1177. type: "http",
  1178. url: "https://mcp.example.test/mcp",
  1179. oauth: {
  1180. type: "authorization_code",
  1181. clientName: "ZCode",
  1182. },
  1183. });
  1184. let authorizationUrl: string | undefined;
  1185. for (let attempt = 0; attempt < 20; attempt += 1) {
  1186. const status = await adapter.status();
  1187. authorizationUrl = status.notion?.authorization?.authorizationUrl;
  1188. if (authorizationUrl) break;
  1189. await new Promise((resolve) => setTimeout(resolve, 10));
  1190. }
  1191. expect(authorizationUrl).toBe("https://auth.example.test/authorize?state=state_test");
  1192. resolveConnect();
  1193. await expect(connect).resolves.toMatchObject({
  1194. status: "connected",
  1195. toolCount: 0,
  1196. });
  1197. await adapter.close();
  1198. });
  1199. it("reuses an unchanged configured connection while OAuth authorization is pending", async () => {
  1200. const { release: resolveConnect } = stubInteractiveAuthorization(
  1201. "https://auth.example.test/authorize?state=stable_state",
  1202. );
  1203. const adapter = createMcpAdapter();
  1204. const firstConnect = adapter.connectConfiguredServers({
  1205. notion: {
  1206. type: "http",
  1207. url: "https://mcp.example.test/mcp",
  1208. oauth: {
  1209. type: "authorization_code",
  1210. clientName: "ZCode",
  1211. },
  1212. },
  1213. });
  1214. let authorizationUrl: string | undefined;
  1215. for (let attempt = 0; attempt < 20; attempt += 1) {
  1216. const status = await adapter.status();
  1217. authorizationUrl = status.notion?.authorization?.authorizationUrl;
  1218. if (authorizationUrl) break;
  1219. await new Promise((resolve) => setTimeout(resolve, 10));
  1220. }
  1221. const secondConnect = adapter.connectConfiguredServers({
  1222. notion: {
  1223. type: "http",
  1224. url: "https://mcp.example.test/mcp",
  1225. oauth: {
  1226. type: "authorization_code",
  1227. clientName: "ZCode",
  1228. },
  1229. },
  1230. });
  1231. await Promise.resolve();
  1232. expect(authorizationUrl).toBe("https://auth.example.test/authorize?state=stable_state");
  1233. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  1234. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  1235. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  1236. expect(capturedHttpOptions).toHaveLength(1);
  1237. await expect(adapter.status()).resolves.toMatchObject({
  1238. notion: {
  1239. authorization: {
  1240. authorizationUrl: "https://auth.example.test/authorize?state=stable_state",
  1241. },
  1242. status: "connecting",
  1243. },
  1244. });
  1245. resolveConnect();
  1246. await expect(Promise.all([firstConnect, secondConnect])).resolves.toMatchObject([
  1247. { statuses: { notion: { status: "connected" } } },
  1248. { statuses: { notion: { status: "connected" } } },
  1249. ]);
  1250. await adapter.close();
  1251. });
  1252. it("keeps a reused OAuth connection alive when a bounded caller times out", async () => {
  1253. const { release: resolveConnect } = stubInteractiveAuthorization(
  1254. "https://auth.example.test/authorize?state=shared_timeout_state",
  1255. );
  1256. const adapter = createMcpAdapter();
  1257. const servers = {
  1258. notion: {
  1259. type: "http" as const,
  1260. url: "https://mcp.example.test/mcp",
  1261. oauth: {
  1262. type: "authorization_code" as const,
  1263. clientName: "ZCode",
  1264. },
  1265. },
  1266. };
  1267. const settingsConnect = adapter.connectConfiguredServers(servers);
  1268. for (let attempt = 0; attempt < 20; attempt += 1) {
  1269. const status = await adapter.status();
  1270. if (status.notion?.authorization?.authorizationUrl) break;
  1271. await new Promise((resolve) => setTimeout(resolve, 10));
  1272. }
  1273. const sessionConnect = await adapter.connectConfiguredServers(servers, {
  1274. oauthAuthorizationTimeoutMs: 20,
  1275. });
  1276. expect(sessionConnect.statuses.notion).toMatchObject({
  1277. authorization: {
  1278. authorizationUrl: "https://auth.example.test/authorize?state=shared_timeout_state",
  1279. },
  1280. status: "connecting",
  1281. });
  1282. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  1283. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  1284. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  1285. expect(capturedHttpOptions).toHaveLength(1);
  1286. resolveConnect();
  1287. await expect(settingsConnect).resolves.toMatchObject({
  1288. statuses: { notion: { status: "connected" } },
  1289. });
  1290. await adapter.close();
  1291. });
  1292. it("only cancels the caller waiter when a reused OAuth connection is aborted", async () => {
  1293. const { release: resolveConnect } = stubInteractiveAuthorization(
  1294. "https://auth.example.test/authorize?state=shared_abort_state",
  1295. );
  1296. const adapter = createMcpAdapter();
  1297. const servers = {
  1298. notion: {
  1299. type: "http" as const,
  1300. url: "https://mcp.example.test/mcp",
  1301. oauth: {
  1302. type: "authorization_code" as const,
  1303. clientName: "ZCode",
  1304. },
  1305. },
  1306. };
  1307. const settingsConnect = adapter.connectConfiguredServers(servers);
  1308. for (let attempt = 0; attempt < 20; attempt += 1) {
  1309. const status = await adapter.status();
  1310. if (status.notion?.authorization?.authorizationUrl) break;
  1311. await new Promise((resolve) => setTimeout(resolve, 10));
  1312. }
  1313. const abortController = new AbortController();
  1314. const sessionConnect = adapter.connectConfiguredServers(servers, {
  1315. signal: abortController.signal,
  1316. });
  1317. abortController.abort(new Error("session stopped"));
  1318. await expect(sessionConnect).resolves.toMatchObject({
  1319. statuses: {
  1320. notion: {
  1321. authorization: {
  1322. authorizationUrl: "https://auth.example.test/authorize?state=shared_abort_state",
  1323. },
  1324. status: "connecting",
  1325. },
  1326. },
  1327. });
  1328. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  1329. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  1330. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  1331. expect(capturedHttpOptions).toHaveLength(1);
  1332. resolveConnect();
  1333. await expect(settingsConnect).resolves.toMatchObject({
  1334. statuses: { notion: { status: "connected" } },
  1335. });
  1336. await adapter.close();
  1337. });
  1338. it("treats per-connect OAuth authorization timeout as a caller budget, not a transaction kill", async () => {
  1339. let startAuthorization!: () => void;
  1340. const beforeAuthorization = new Promise<void>((resolve) => {
  1341. startAuthorization = resolve;
  1342. });
  1343. const { release, ready } = stubInteractiveAuthorization(
  1344. "https://auth.example.test/authorize?state=state_test",
  1345. beforeAuthorization,
  1346. );
  1347. const adapter = createMcpAdapter();
  1348. const startedAt = Date.now();
  1349. try {
  1350. const status = await adapter.connectServer(
  1351. "notion",
  1352. {
  1353. type: "http",
  1354. url: "https://mcp.example.test/mcp",
  1355. timeoutMs: 2_000,
  1356. oauth: { type: "authorization_code", clientName: "ZCode" },
  1357. },
  1358. { oauthAuthorizationTimeoutMs: 20 },
  1359. );
  1360. // URL 发布含异步存储,不能假定它比 20ms caller 预算更快;事务应在 caller 返回后继续。
  1361. expect(status).toMatchObject({ status: "connecting" });
  1362. expect(status.authorization).toBeUndefined();
  1363. expect(Date.now() - startedAt).toBeLessThan(1_000);
  1364. expect(transportFinishAuthMock).not.toHaveBeenCalled();
  1365. startAuthorization();
  1366. await ready;
  1367. await expect(adapter.status()).resolves.toMatchObject({
  1368. notion: {
  1369. authorization: {
  1370. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  1371. },
  1372. status: "connecting",
  1373. },
  1374. });
  1375. release();
  1376. await vi.waitFor(async () => {
  1377. expect(await adapter.status()).toMatchObject({ notion: { status: "connected" } });
  1378. });
  1379. } finally {
  1380. startAuthorization();
  1381. release();
  1382. await adapter.close();
  1383. }
  1384. });
  1385. it("keeps runtime OAuth recovery alive after the triggering caller times out", async () => {
  1386. let startAuthorization!: () => void;
  1387. const beforeAuthorization = new Promise<void>((resolve) => {
  1388. startAuthorization = resolve;
  1389. });
  1390. let markReady!: () => void;
  1391. const ready = new Promise<void>((resolve) => {
  1392. markReady = resolve;
  1393. });
  1394. let releaseAuthorization!: () => void;
  1395. const authorizationGate = new Promise<void>((resolve) => {
  1396. releaseAuthorization = resolve;
  1397. });
  1398. authMock.mockImplementation(async (provider: unknown) => {
  1399. const interactiveProvider = provider as {
  1400. redirectToAuthorization(url: URL): Promise<void>;
  1401. state(): Promise<string>;
  1402. };
  1403. const authorizationUrl = new URL("https://auth.example.test/authorize");
  1404. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  1405. await beforeAuthorization;
  1406. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  1407. markReady();
  1408. await authorizationGate;
  1409. return "AUTHORIZED" as const;
  1410. });
  1411. clientCallToolMock
  1412. .mockRejectedValueOnce(new UnauthorizedError())
  1413. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  1414. const adapter = createMcpAdapter();
  1415. await adapter.connectServer("runtime", {
  1416. oauth: {
  1417. type: "authorization_code",
  1418. },
  1419. type: "http",
  1420. url: "https://mcp.example.test/mcp",
  1421. });
  1422. const call = adapter.callTool(
  1423. {
  1424. serverName: "runtime",
  1425. toolName: "oauth_ping",
  1426. },
  1427. { timeoutMs: 20 },
  1428. );
  1429. try {
  1430. await expect(observePromiseWithin(call, 200)).resolves.toMatchObject({
  1431. reason: {
  1432. name: "McpTimeoutError",
  1433. },
  1434. status: "rejected",
  1435. });
  1436. // 显式让 caller 先超时,再发布 URL,避免靠机器负载决定断言先后。
  1437. startAuthorization();
  1438. await ready;
  1439. await expect(adapter.status()).resolves.toMatchObject({
  1440. runtime: {
  1441. authorization: {
  1442. authorizationUrl: expect.stringContaining("https://auth.example.test/authorize"),
  1443. },
  1444. status: "connecting",
  1445. },
  1446. });
  1447. releaseAuthorization();
  1448. for (let attempt = 0; attempt < 50; attempt += 1) {
  1449. const status = await adapter.status();
  1450. if (status.runtime?.status === "connected") break;
  1451. await new Promise((resolve) => setTimeout(resolve, 10));
  1452. }
  1453. await expect(adapter.status()).resolves.toMatchObject({
  1454. runtime: { status: "connected" },
  1455. });
  1456. await expect(
  1457. adapter.callTool(
  1458. {
  1459. serverName: "runtime",
  1460. toolName: "oauth_ping",
  1461. },
  1462. { timeoutMs: 200 },
  1463. ),
  1464. ).resolves.toMatchObject({
  1465. content: [{ text: "ok", type: "text" }],
  1466. });
  1467. expect(authMock).toHaveBeenCalledTimes(1);
  1468. // 原 caller 已经超时,后台 recovery 只负责重连;不会替超时 caller 再执行工具。
  1469. expect(clientCallToolMock).toHaveBeenCalledTimes(2);
  1470. } finally {
  1471. startAuthorization();
  1472. releaseAuthorization();
  1473. await Promise.allSettled([call]);
  1474. await adapter.close();
  1475. }
  1476. });
  1477. it("shares one runtime OAuth recovery across concurrent tool callers", async () => {
  1478. let releaseAuthorization!: () => void;
  1479. const authorizationGate = new Promise<void>((resolve) => {
  1480. releaseAuthorization = resolve;
  1481. });
  1482. authMock.mockImplementation(async (provider: unknown) => {
  1483. const interactiveProvider = provider as {
  1484. redirectToAuthorization(url: URL): Promise<void>;
  1485. state(): Promise<string>;
  1486. };
  1487. const authorizationUrl = new URL("https://auth.example.test/authorize");
  1488. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  1489. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  1490. await authorizationGate;
  1491. return "AUTHORIZED" as const;
  1492. });
  1493. clientCallToolMock
  1494. .mockRejectedValueOnce(new UnauthorizedError())
  1495. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  1496. const adapter = createMcpAdapter();
  1497. await adapter.connectServer("runtime", {
  1498. oauth: {
  1499. type: "authorization_code",
  1500. },
  1501. type: "http",
  1502. url: "https://mcp.example.test/mcp",
  1503. });
  1504. const firstCall = adapter.callTool(
  1505. {
  1506. serverName: "runtime",
  1507. toolName: "oauth_ping",
  1508. },
  1509. { timeoutMs: 2_000 },
  1510. );
  1511. try {
  1512. for (let attempt = 0; attempt < 50; attempt += 1) {
  1513. const status = await adapter.status();
  1514. if (status.runtime?.authorization?.authorizationUrl) break;
  1515. await new Promise((resolve) => setTimeout(resolve, 10));
  1516. }
  1517. await expect(adapter.status()).resolves.toMatchObject({
  1518. runtime: {
  1519. authorization: {
  1520. authorizationUrl: expect.stringContaining("https://auth.example.test/authorize"),
  1521. },
  1522. status: "connecting",
  1523. },
  1524. });
  1525. const secondCall = adapter.callTool(
  1526. {
  1527. serverName: "runtime",
  1528. toolName: "oauth_ping",
  1529. },
  1530. { timeoutMs: 2_000 },
  1531. );
  1532. await Promise.resolve();
  1533. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  1534. releaseAuthorization();
  1535. await expect(Promise.all([firstCall, secondCall])).resolves.toMatchObject([
  1536. { content: [{ text: "ok", type: "text" }] },
  1537. { content: [{ text: "ok", type: "text" }] },
  1538. ]);
  1539. expect(authMock).toHaveBeenCalledTimes(1);
  1540. // 第一次认证失败 + first caller 的一次安全重试 + second caller 的首次实际调用。
  1541. expect(clientCallToolMock).toHaveBeenCalledTimes(3);
  1542. await expect(adapter.status()).resolves.toMatchObject({
  1543. runtime: { status: "connected" },
  1544. });
  1545. } finally {
  1546. releaseAuthorization();
  1547. await Promise.allSettled([firstCall]);
  1548. await adapter.close();
  1549. }
  1550. });
  1551. it("does not let a caller abort close the shared runtime OAuth callback listener", async () => {
  1552. let authorizationContext:
  1553. | {
  1554. authorizationUrl: string;
  1555. redirectUrl: string;
  1556. }
  1557. | undefined;
  1558. authMock.mockImplementation(
  1559. async (provider: unknown, options?: { authorizationCode?: string }) => {
  1560. if (options?.authorizationCode) return "AUTHORIZED" as const;
  1561. const interactiveProvider = provider as {
  1562. redirectToAuthorization(url: URL): Promise<void>;
  1563. state(): Promise<string>;
  1564. };
  1565. const authorizationUrl = new URL("https://auth.example.test/authorize");
  1566. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  1567. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  1568. return "REDIRECT" as never;
  1569. },
  1570. );
  1571. clientCallToolMock
  1572. .mockRejectedValueOnce(new UnauthorizedError())
  1573. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  1574. const adapter = createMcpAdapter({
  1575. mcpOAuth: {
  1576. onAuthorizationRequired: async (context) => {
  1577. authorizationContext = context;
  1578. },
  1579. },
  1580. });
  1581. await adapter.connectServer("runtime", {
  1582. oauth: {
  1583. type: "authorization_code",
  1584. },
  1585. type: "http",
  1586. url: "https://mcp.example.test/mcp",
  1587. });
  1588. const abortController = new AbortController();
  1589. const call = adapter.callTool(
  1590. {
  1591. serverName: "runtime",
  1592. toolName: "oauth_ping",
  1593. },
  1594. {
  1595. signal: abortController.signal,
  1596. timeoutMs: 2_000,
  1597. },
  1598. );
  1599. try {
  1600. for (let attempt = 0; attempt < 50; attempt += 1) {
  1601. if (authorizationContext) break;
  1602. await new Promise((resolve) => setTimeout(resolve, 10));
  1603. }
  1604. expect(authorizationContext).toBeDefined();
  1605. abortController.abort(new Error("caller stopped"));
  1606. await expect(observePromiseWithin(call, 200)).resolves.toMatchObject({
  1607. reason: {
  1608. message: "caller stopped",
  1609. },
  1610. status: "rejected",
  1611. });
  1612. const callbackUrl = new URL(authorizationContext!.redirectUrl);
  1613. callbackUrl.searchParams.set("code", "authorized-after-caller-abort");
  1614. callbackUrl.searchParams.set(
  1615. "state",
  1616. new URL(authorizationContext!.authorizationUrl).searchParams.get("state") ?? "",
  1617. );
  1618. await expect(fetch(callbackUrl)).resolves.toMatchObject({ ok: true });
  1619. for (let attempt = 0; attempt < 50; attempt += 1) {
  1620. const status = await adapter.status();
  1621. if (status.runtime?.status === "connected") break;
  1622. await new Promise((resolve) => setTimeout(resolve, 10));
  1623. }
  1624. await expect(adapter.status()).resolves.toMatchObject({
  1625. runtime: { status: "connected" },
  1626. });
  1627. expect(authMock).toHaveBeenCalledTimes(2);
  1628. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  1629. } finally {
  1630. await Promise.allSettled([call]);
  1631. await adapter.close();
  1632. }
  1633. });
  1634. it("converges Phase 2 orchestration errors to a retryable failed server status", async () => {
  1635. const credentialError = new Error("Unable to read shared ZCode credentials");
  1636. const credentialStore = {
  1637. filePath: "/tmp/zcode-unreadable-credentials.json",
  1638. load: vi.fn(async () => {
  1639. throw credentialError;
  1640. }),
  1641. loadMany: vi.fn(async () => {
  1642. throw credentialError;
  1643. }),
  1644. } as unknown as SharedZCodeCredentialStore;
  1645. clientConnectMock.mockRejectedValue(new UnauthorizedError());
  1646. const adapter = createMcpAdapter({
  1647. mcpOAuth: {
  1648. credentialStore,
  1649. },
  1650. });
  1651. const config = {
  1652. oauth: {
  1653. type: "authorization_code" as const,
  1654. },
  1655. type: "http" as const,
  1656. url: "https://mcp.example.test/mcp",
  1657. };
  1658. try {
  1659. await expect(adapter.connectConfiguredServers({ broken: config })).resolves.toMatchObject({
  1660. statuses: {
  1661. broken: {
  1662. error: "Unable to read shared ZCode credentials",
  1663. failureKind: "oauth_authorization_failed",
  1664. status: "failed",
  1665. },
  1666. },
  1667. });
  1668. await expect(adapter.status()).resolves.toMatchObject({
  1669. broken: {
  1670. failureKind: "oauth_authorization_failed",
  1671. status: "failed",
  1672. },
  1673. });
  1674. await expect(adapter.connectConfiguredServers({ broken: config })).resolves.toMatchObject({
  1675. statuses: {
  1676. broken: {
  1677. failureKind: "oauth_authorization_failed",
  1678. status: "failed",
  1679. },
  1680. },
  1681. });
  1682. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  1683. } finally {
  1684. await adapter.close();
  1685. }
  1686. });
  1687. it("only opens OAuth authorization URL when an opener is injected", async () => {
  1688. const openAuthorizationUrl = vi.fn(async () => {});
  1689. const { release: resolveConnect } = stubInteractiveAuthorization(
  1690. "https://auth.example.test/authorize?state=state_test",
  1691. );
  1692. const adapter = createMcpAdapter({
  1693. mcpOAuth: {
  1694. openAuthorizationUrl,
  1695. },
  1696. });
  1697. const connect = adapter.connectServer("notion", {
  1698. type: "http",
  1699. url: "https://mcp.example.test/mcp",
  1700. oauth: {
  1701. type: "authorization_code",
  1702. clientName: "ZCode",
  1703. },
  1704. });
  1705. for (let attempt = 0; attempt < 20; attempt += 1) {
  1706. const status = await adapter.status();
  1707. if (status.notion?.authorization?.authorizationUrl) break;
  1708. await new Promise((resolve) => setTimeout(resolve, 10));
  1709. }
  1710. expect(openAuthorizationUrl).toHaveBeenCalledWith(
  1711. expect.objectContaining({
  1712. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  1713. serverName: "notion",
  1714. }),
  1715. );
  1716. resolveConnect();
  1717. await expect(connect).resolves.toMatchObject({
  1718. status: "connected",
  1719. toolCount: 0,
  1720. });
  1721. await adapter.close();
  1722. });
  1723. });