mcp.test.ts 59 KB

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