mcp.test.ts 54 KB

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