mcp.test.ts 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459
  1. import {
  2. createMcpDeadline,
  3. McpTimeoutError,
  4. waitWithinMcpDeadline,
  5. withTimeout,
  6. } from "../src/mcp/timeout.js";
  7. import { createMcpConnectionPool } from "../src/mcp/pool.js";
  8. import { delimiter, dirname } from "node:path";
  9. import { beforeEach, describe, expect, it, vi } from "vitest";
  10. import { SdkError, SdkErrorCode, UnauthorizedError } from "@modelcontextprotocol/client";
  11. import { ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY } from "@zcode/shared";
  12. import type { SharedZCodeCredentialStore } from "../src/auth/shared-credentials.js";
  13. const {
  14. capturedClientInfo,
  15. capturedClients,
  16. capturedHttpOptions,
  17. capturedSseOptions,
  18. capturedStdioOptions,
  19. capturedStdioStderrHandlers,
  20. capturedClientOptions,
  21. clientCloseMock,
  22. clientCallToolMock,
  23. clientConnectMock,
  24. clientListToolsMock,
  25. clientPingMock,
  26. clientSubscribeMock,
  27. clientUnsubscribeMock,
  28. transportCloseMock,
  29. transportFinishAuthMock,
  30. authMock,
  31. } = vi.hoisted(() => ({
  32. capturedClientInfo: [] as Array<{ name: string; version: string }>,
  33. capturedClients: [] as Array<{
  34. notificationHandlers: Map<string, (notification: unknown) => void>;
  35. onclose?: () => void;
  36. }>,
  37. capturedHttpOptions: [] as unknown[],
  38. capturedSseOptions: [] as unknown[],
  39. capturedStdioOptions: [] as unknown[],
  40. capturedStdioStderrHandlers: [] as Array<(chunk: Buffer) => void>,
  41. capturedClientOptions: [] as unknown[],
  42. clientCloseMock: vi.fn(async () => {}),
  43. clientCallToolMock: vi.fn(async () => ({
  44. content: [{ type: "text", text: "ok" }],
  45. })),
  46. clientConnectMock: vi.fn(async () => {}),
  47. clientListToolsMock: vi.fn(async () => ({ tools: [] })),
  48. clientPingMock: vi.fn(async () => ({})),
  49. clientSubscribeMock: vi.fn(async () => ({})),
  50. clientUnsubscribeMock: vi.fn(async () => ({})),
  51. transportCloseMock: vi.fn(async () => {}),
  52. transportFinishAuthMock: vi.fn(async () => {}),
  53. authMock: vi.fn(async () => "AUTHORIZED" as const),
  54. }));
  55. vi.mock("@modelcontextprotocol/client", async (importOriginal) => {
  56. const actual = await importOriginal<typeof import("@modelcontextprotocol/client")>();
  57. return {
  58. ...actual,
  59. auth: authMock,
  60. Client: class {
  61. readonly close = clientCloseMock;
  62. readonly callTool = clientCallToolMock;
  63. readonly connect = clientConnectMock;
  64. readonly listTools = clientListToolsMock;
  65. readonly ping = clientPingMock;
  66. readonly subscribeResource = clientSubscribeMock;
  67. readonly unsubscribeResource = clientUnsubscribeMock;
  68. getServerCapabilities() {
  69. return { resources: { subscribe: true } };
  70. }
  71. readonly notificationHandlers = new Map<string, (notification: unknown) => void>();
  72. onclose?: () => void;
  73. setNotificationHandler(method: string, handler: (notification: unknown) => void) {
  74. this.notificationHandlers.set(method, handler);
  75. }
  76. constructor(info: { name: string; version: string }, options?: unknown) {
  77. capturedClientInfo.push(info);
  78. capturedClientOptions.push(options);
  79. capturedClients.push(this);
  80. }
  81. getProtocolEra() {
  82. const options = capturedClientOptions.at(-1) as {
  83. versionNegotiation?: { mode?: unknown };
  84. };
  85. return options?.versionNegotiation?.mode === "legacy" ? "legacy" : "modern";
  86. }
  87. getNegotiatedProtocolVersion() {
  88. const options = capturedClientOptions.at(-1) as {
  89. versionNegotiation?: { mode?: unknown };
  90. };
  91. return options?.versionNegotiation?.mode === "legacy" ? "2025-11-25" : "2026-07-28";
  92. }
  93. },
  94. SSEClientTransport: class {
  95. readonly close = transportCloseMock;
  96. readonly finishAuth = transportFinishAuthMock;
  97. constructor(_url: URL, options: unknown) {
  98. capturedSseOptions.push(options);
  99. }
  100. },
  101. StreamableHTTPClientTransport: class {
  102. readonly close = transportCloseMock;
  103. readonly finishAuth = transportFinishAuthMock;
  104. constructor(_url: URL, options: unknown) {
  105. capturedHttpOptions.push(options);
  106. }
  107. },
  108. };
  109. });
  110. vi.mock("@modelcontextprotocol/client/stdio", () => ({
  111. StdioClientTransport: class {
  112. readonly close = transportCloseMock;
  113. readonly pid = 42_424;
  114. readonly stderr = {
  115. on: vi.fn((event: "data", handler: (chunk: Buffer) => void) => {
  116. if (event === "data") capturedStdioStderrHandlers.push(handler);
  117. }),
  118. };
  119. constructor(options: unknown) {
  120. capturedStdioOptions.push(options);
  121. }
  122. },
  123. }));
  124. import { createMcpAdapter } from "../src/mcp/index.js";
  125. import { createMcpTelemetryTracker } from "../src/mcp/telemetry.js";
  126. // 宿主内建的 stdio server(node_repl):source 只由宿主生成。
  127. const BUILT_IN_STDIO_CONFIG = {
  128. command: "node",
  129. source: { kind: "builtin" as const },
  130. type: "stdio" as const,
  131. };
  132. /**
  133. * 把 Phase 1 建连做成认证失败,并接管 Phase 2 的 `auth()`:调用 provider 的
  134. * `redirectToAuthorization()` 暴露授权 URL,然后阻塞在 gate 上,直到测试调用 `release()`。
  135. *
  136. * 修复原因:授权 URL 的归属已经从「Phase 1 provider 自己 redirect」改为「Phase 2 事务发布」,
  137. * 所以这些用例必须走 connect 失败 → 分类 → Phase 2 这条新链路。
  138. */
  139. function stubInteractiveAuthorization(
  140. authorizationUrl: string,
  141. beforeAuthorization?: Promise<void>,
  142. ): { release: () => void; ready: Promise<void> } {
  143. let markReady!: () => void;
  144. const ready = new Promise<void>((resolve) => {
  145. markReady = resolve;
  146. });
  147. let release!: () => void;
  148. const gate = new Promise<void>((resolve) => {
  149. release = resolve;
  150. });
  151. let connectAttempts = 0;
  152. clientConnectMock.mockImplementation(async () => {
  153. connectAttempts += 1;
  154. // 第一次建连以确定性认证错误失败,触发 Phase 2;授权完成后的重连必须成功。
  155. if (connectAttempts === 1) throw new UnauthorizedError();
  156. });
  157. authMock.mockImplementation(async (provider: unknown) => {
  158. const interactiveProvider = provider as {
  159. redirectToAuthorization(url: URL): Promise<void>;
  160. };
  161. await beforeAuthorization;
  162. await interactiveProvider.redirectToAuthorization(new URL(authorizationUrl));
  163. markReady();
  164. await gate;
  165. return "AUTHORIZED" as const;
  166. });
  167. return { release, ready };
  168. }
  169. async function observePromiseWithin<T>(
  170. promise: Promise<T>,
  171. timeoutMs: number,
  172. ): Promise<
  173. | { status: "fulfilled"; value: T }
  174. | { reason: unknown; status: "rejected" }
  175. | { status: "pending" }
  176. > {
  177. let timeoutId: ReturnType<typeof setTimeout> | undefined;
  178. const observed = promise.then(
  179. (value) => ({ status: "fulfilled" as const, value }),
  180. (reason: unknown) => ({ reason, status: "rejected" as const }),
  181. );
  182. try {
  183. return await Promise.race([
  184. observed,
  185. new Promise<{ status: "pending" }>((resolve) => {
  186. timeoutId = setTimeout(() => resolve({ status: "pending" }), timeoutMs);
  187. }),
  188. ]);
  189. } finally {
  190. if (timeoutId !== undefined) clearTimeout(timeoutId);
  191. }
  192. }
  193. describe("createMcpAdapter", () => {
  194. beforeEach(() => {
  195. capturedClientInfo.length = 0;
  196. capturedHttpOptions.length = 0;
  197. capturedSseOptions.length = 0;
  198. capturedStdioOptions.length = 0;
  199. capturedStdioStderrHandlers.length = 0;
  200. capturedClientOptions.length = 0;
  201. capturedClients.length = 0;
  202. clientCloseMock.mockClear();
  203. clientCallToolMock.mockClear();
  204. clientConnectMock.mockClear();
  205. clientListToolsMock.mockReset();
  206. clientSubscribeMock.mockReset().mockResolvedValue({});
  207. clientUnsubscribeMock.mockReset().mockResolvedValue({});
  208. clientPingMock.mockClear();
  209. clientPingMock.mockResolvedValue({});
  210. transportCloseMock.mockClear();
  211. transportFinishAuthMock.mockClear();
  212. authMock.mockClear();
  213. authMock.mockResolvedValue("AUTHORIZED");
  214. clientConnectMock.mockResolvedValue(undefined);
  215. clientListToolsMock.mockResolvedValue({ tools: [] });
  216. clientCallToolMock.mockResolvedValue({
  217. content: [{ type: "text", text: "ok" }],
  218. });
  219. });
  220. it("close waits for cancelled handshake resource cleanup before returning", async () => {
  221. const started = Promise.withResolvers<void>();
  222. const cleanupStarted = Promise.withResolvers<void>();
  223. const cleaned = Promise.withResolvers<void>();
  224. clientConnectMock.mockImplementationOnce(async () => {
  225. started.resolve();
  226. await new Promise(() => {});
  227. });
  228. clientCloseMock.mockImplementationOnce(async () => {
  229. cleanupStarted.resolve();
  230. await cleaned.promise;
  231. });
  232. const adapter = createMcpAdapter();
  233. const connecting = adapter.connectServer("slow", {
  234. type: "http",
  235. url: "https://mcp.example.test/mcp",
  236. });
  237. await started.promise;
  238. let settled = false;
  239. const closing = adapter.close().then(() => {
  240. settled = true;
  241. });
  242. await cleanupStarted.promise;
  243. for (let i = 0; i < 5; i++) await Promise.resolve();
  244. expect(settled).toBe(false);
  245. cleaned.resolve();
  246. await closing;
  247. await connecting;
  248. expect(await adapter.status()).toEqual({});
  249. });
  250. it("does not start a connection while the adapter is closing", async () => {
  251. const adapter = createMcpAdapter();
  252. await adapter.connectServer("first", { type: "stdio", command: "node" });
  253. const closeGate = Promise.withResolvers<void>();
  254. const connectGate = Promise.withResolvers<void>();
  255. clientCloseMock.mockImplementationOnce(() => closeGate.promise);
  256. const closing = adapter.close();
  257. await vi.waitFor(() => expect(clientCloseMock).toHaveBeenCalled());
  258. clientConnectMock.mockClear();
  259. // 持久实现由 beforeEach 复位;未被调用的 once 实现会串到下一个用例。
  260. clientConnectMock.mockImplementation(() => connectGate.promise);
  261. // 修复前关闭期间仍会登记新记录;close 清空记录后,连接完成时读不到记录而抛 TypeError。
  262. const late = adapter.connectServer("late", { type: "stdio", command: "node" });
  263. closeGate.resolve();
  264. await closing;
  265. connectGate.resolve();
  266. await expect(late).resolves.toMatchObject({ status: "disconnected" });
  267. expect(clientConnectMock).not.toHaveBeenCalled();
  268. expect(await adapter.status()).toEqual({});
  269. });
  270. it("waits for the existing App connection without exposing a premature snapshot or reconnecting", async () => {
  271. const gate = Promise.withResolvers<void>();
  272. clientConnectMock.mockImplementationOnce(() => gate.promise);
  273. const adapter = createMcpAdapter();
  274. const connecting = adapter.connectServer("fixture", { type: "stdio", command: "node" });
  275. await vi.waitFor(() => expect(clientConnectMock).toHaveBeenCalledOnce());
  276. expect(adapter.appConnectionSnapshot?.("fixture")).toBeNull();
  277. const settled = vi.fn();
  278. const opening = adapter.waitForAppConnection!("fixture").then(settled);
  279. await Promise.resolve();
  280. expect(settled).not.toHaveBeenCalled();
  281. gate.resolve();
  282. await connecting;
  283. await opening;
  284. expect(settled).toHaveBeenCalledWith(adapter.appConnectionSnapshot?.("fixture"));
  285. expect(settled.mock.calls[0]?.[0]).not.toBeNull();
  286. expect(clientConnectMock).toHaveBeenCalledOnce();
  287. await adapter.close();
  288. });
  289. it("does not issue an App connection for an absent or failed server", async () => {
  290. const adapter = createMcpAdapter();
  291. expect(await adapter.waitForAppConnection!("missing")).toBeNull();
  292. clientConnectMock.mockRejectedValueOnce(new Error("fixture startup failure"));
  293. await adapter.connectServer("fixture", { type: "stdio", command: "node" });
  294. expect(await adapter.waitForAppConnection!("fixture")).toBeNull();
  295. expect(clientConnectMock).toHaveBeenCalledOnce();
  296. await adapter.close();
  297. });
  298. // 相同配置复用当前连接任务,只有配置变更才换代;换代后旧等待者不能拿到新连接。
  299. it("rejects an App startup waiter after the connection generation is replaced", async () => {
  300. const gate = Promise.withResolvers<void>();
  301. clientConnectMock.mockImplementationOnce(() => gate.promise);
  302. const adapter = createMcpAdapter();
  303. const config = { type: "stdio" as const, command: "node" };
  304. const connecting = adapter.connectServer("fixture", config);
  305. await vi.waitFor(() => expect(clientConnectMock).toHaveBeenCalledOnce());
  306. const opening = adapter.waitForAppConnection!("fixture");
  307. const replaced = adapter.connectServer("fixture", { ...config, env: { VERSION: "2" } });
  308. gate.resolve();
  309. await Promise.all([connecting, replaced]);
  310. expect(await opening).toBeNull();
  311. expect(adapter.appConnectionSnapshot?.("fixture")).not.toBeNull();
  312. await adapter.close();
  313. });
  314. /** 在用例内收集未处理 rejection,不依赖测试框架的全局检测。 */
  315. async function collectUnhandledRejections(run: () => Promise<void>): Promise<unknown[]> {
  316. const leaked: unknown[] = [];
  317. const listener = (reason: unknown) => leaked.push(reason);
  318. process.on("unhandledRejection", listener);
  319. try {
  320. await run();
  321. // 未处理 rejection 在下一轮事件循环前派发。
  322. await new Promise<void>((resolve) => setImmediate(resolve));
  323. } finally {
  324. process.off("unhandledRejection", listener);
  325. }
  326. return leaked;
  327. }
  328. it.each(["cancelled", "expired"] as const)(
  329. "observes a shared task rejection after its waiter is already %s",
  330. async (mode) => {
  331. const task = Promise.withResolvers<void>();
  332. const abort = new AbortController();
  333. abort.abort(new Error("Caller left"));
  334. const waiting = Promise.resolve().then(() =>
  335. mode === "cancelled"
  336. ? withTimeout(task.promise, 1000, "Deadline expired", abort.signal)
  337. : waitWithinMcpDeadline(task.promise, createMcpDeadline(0), "Deadline expired"),
  338. );
  339. const leaked = await collectUnhandledRejections(async () => {
  340. await expect(waiting).rejects.toThrow(
  341. mode === "cancelled" ? "Caller left" : "Deadline expired",
  342. );
  343. task.reject(new Error("Shared task failed after waiter left"));
  344. });
  345. expect(leaked).toEqual([]);
  346. },
  347. );
  348. it("observes subscription work when cancellation and disconnect overlap", async () => {
  349. const adapter = createMcpAdapter();
  350. try {
  351. await adapter.connectServer("demo", { type: "http", url: "https://example.com/mcp" });
  352. const abort = new AbortController();
  353. const subscription = adapter.subscribeResource!(
  354. {
  355. serverName: "demo",
  356. uri: "test://closing",
  357. subscriberKey: "A:scope:1",
  358. },
  359. { signal: abort.signal },
  360. ).catch((error: unknown) => error);
  361. const leaked = await collectUnhandledRejections(async () => {
  362. abort.abort(new Error("Caller closing"));
  363. await adapter.disconnectServer("demo");
  364. expect(await subscription).toEqual(new Error("Caller closing"));
  365. });
  366. expect(leaked).toEqual([]);
  367. } finally {
  368. await adapter.close();
  369. }
  370. });
  371. it("preserves a committed subscription when a duplicate caller is cancelled", async () => {
  372. const adapter = createMcpAdapter();
  373. const request = {
  374. serverName: "demo",
  375. uri: "test://existing",
  376. subscriberKey: "session:scope:1",
  377. };
  378. try {
  379. await adapter.connectServer("demo", { type: "http", url: "https://example.com/mcp" });
  380. await adapter.subscribeResource!(request);
  381. const abort = new AbortController();
  382. const duplicate = adapter.subscribeResource!(request, { signal: abort.signal });
  383. abort.abort(new Error("Duplicate cancelled"));
  384. await expect(duplicate).rejects.toThrow("Duplicate cancelled");
  385. expect(await adapter.unsubscribeResourcesBySubscriber!("session:")).toBe(1);
  386. await adapter.unsubscribeResource!(request);
  387. expect(clientUnsubscribeMock).toHaveBeenCalledTimes(1);
  388. expect(clientSubscribeMock).toHaveBeenCalledTimes(1);
  389. } finally {
  390. await adapter.close();
  391. }
  392. });
  393. it("keeps another pending subscription with the same key when one caller leaves", async () => {
  394. const entered = Promise.withResolvers<void>(),
  395. release = Promise.withResolvers<void>();
  396. clientSubscribeMock.mockImplementationOnce(async () => {
  397. entered.resolve();
  398. await release.promise;
  399. return {};
  400. });
  401. const adapter = createMcpAdapter();
  402. const request = {
  403. serverName: "demo",
  404. uri: "test://concurrent",
  405. subscriberKey: "session:scope:1",
  406. };
  407. try {
  408. await adapter.connectServer("demo", { type: "http", url: "https://example.com/mcp" });
  409. const abort = new AbortController();
  410. const first = adapter.subscribeResource!(request, { signal: abort.signal });
  411. await entered.promise;
  412. const second = adapter.subscribeResource!(request);
  413. // 首个 RPC 仍由 gate 阻塞,让两个 caller 都登记完再取消其中一个。
  414. await new Promise<void>((resolve) => setImmediate(resolve));
  415. abort.abort(new Error("First caller left"));
  416. await expect(first).rejects.toThrow("First caller left");
  417. release.resolve();
  418. await second;
  419. expect(clientUnsubscribeMock).not.toHaveBeenCalled();
  420. expect(clientSubscribeMock).toHaveBeenCalledTimes(1);
  421. expect(await adapter.unsubscribeResourcesBySubscriber!("session:")).toBe(1);
  422. } finally {
  423. release.resolve();
  424. await adapter.close();
  425. }
  426. });
  427. it.each(["explicit", "scope"] as const)(
  428. "does not revive a subscription removed by %s cleanup during connection wait",
  429. async (mode) => {
  430. const entered = Promise.withResolvers<void>(),
  431. release = Promise.withResolvers<void>();
  432. clientConnectMock.mockImplementationOnce(async () => {
  433. entered.resolve();
  434. await release.promise;
  435. });
  436. const adapter = createMcpAdapter();
  437. const request = { serverName: "demo", uri: "test://late", subscriberKey: "session:scope:1" };
  438. const connecting = adapter.connectServer("demo", {
  439. type: "http",
  440. url: "https://example.com/mcp",
  441. });
  442. try {
  443. await entered.promise;
  444. const subscribing = adapter.subscribeResource!(request);
  445. if (mode === "scope") await adapter.unsubscribeResourcesBySubscriber!("session:");
  446. else await adapter.unsubscribeResource!(request);
  447. release.resolve();
  448. await Promise.all([connecting, subscribing]);
  449. expect(await adapter.unsubscribeResourcesBySubscriber!("session:")).toBe(0);
  450. expect(clientSubscribeMock).not.toHaveBeenCalled();
  451. } finally {
  452. release.resolve();
  453. await adapter.close();
  454. }
  455. },
  456. );
  457. it.each(["lease", "revalidate", "configured"] as const)(
  458. "keeps a later %s caller independent of the initial connection wait",
  459. async (mode) => {
  460. const entered = Promise.withResolvers<void>();
  461. const release = Promise.withResolvers<void>();
  462. clientConnectMock.mockImplementationOnce(async () => {
  463. entered.resolve();
  464. await release.promise;
  465. });
  466. const adapter = createMcpAdapter();
  467. const pool = createMcpConnectionPool({ createAdapter: () => adapter, idleGraceMs: 0 });
  468. const first = pool.acquireLease(),
  469. second = pool.acquireLease();
  470. const config = { type: "stdio" as const, command: "node", isolation: "workspace" as const };
  471. const scope = { workspaceIdentity: "shared" };
  472. const starting = first.connectServer("demo", config, scope);
  473. try {
  474. await entered.promise;
  475. const controller = new AbortController();
  476. const waiting =
  477. mode === "configured"
  478. ? adapter.connectConfiguredServers({ demo: config }, { signal: controller.signal })
  479. : second.connectServer("demo", config, {
  480. ...scope,
  481. signal: controller.signal,
  482. revalidate: mode === "revalidate",
  483. });
  484. let finished = false;
  485. // 经 pool 租约的取消以 reject 结束本次等待;直接调用 adapter 时返回当前状态。
  486. const settled = waiting.then(
  487. () => "resolved",
  488. () => "rejected",
  489. );
  490. void settled.then(() => {
  491. finished = true;
  492. });
  493. controller.abort();
  494. await new Promise<void>((resolve) => setImmediate(resolve));
  495. expect(finished).toBe(true);
  496. expect(await settled).toBe(mode === "configured" ? "resolved" : "rejected");
  497. expect(adapter.getToolSnapshot().demo.status.status).toBe("connecting");
  498. release.resolve();
  499. await starting;
  500. expect(clientConnectMock).toHaveBeenCalledOnce();
  501. expect((await first.callTool({ serverName: "demo", toolName: "ping" })).content).toEqual([
  502. { type: "text", text: "ok" },
  503. ]);
  504. } finally {
  505. release.resolve();
  506. await starting;
  507. await pool.close();
  508. }
  509. },
  510. );
  511. it.each(["initial", "recovery"] as const)(
  512. "continues a list_changed received during %s discovery without another read or notification",
  513. async (phase) => {
  514. const adapter = createMcpAdapter();
  515. const config = { type: "http" as const, url: "https://mcp.example.test" };
  516. const tool = (name: string) => ({ name, inputSchema: { type: "object", properties: {} } });
  517. const refreshed = Promise.withResolvers<void>();
  518. const off = adapter.onSnapshotChanged!(() => {
  519. if (adapter.getToolSnapshot().demo?.tools?.[0]?.toolName === "new") refreshed.resolve();
  520. });
  521. try {
  522. if (phase === "recovery") await adapter.connectServer("demo", config);
  523. clientListToolsMock.mockImplementationOnce(async () => {
  524. capturedClients.at(-1)!.notificationHandlers.get("notifications/tools/list_changed")!({});
  525. await new Promise<void>((resolve) => setImmediate(resolve));
  526. return { tools: [tool("old")] };
  527. });
  528. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("new")] });
  529. if (phase === "recovery") {
  530. capturedClients.at(-1)!.onclose?.();
  531. await adapter.waitForServer!("demo", { timeoutMs: 1000 });
  532. } else await adapter.connectServer("demo", config);
  533. await withTimeout(refreshed.promise, 300, "dirty discovery was not resumed");
  534. expect(adapter.getToolSnapshot().demo.tools?.[0]?.toolName).toBe("new");
  535. } finally {
  536. off();
  537. await adapter.close();
  538. }
  539. },
  540. );
  541. it("does not inherit a settled caller wait and keeps independent timeout budgets", async () => {
  542. const entered = Promise.withResolvers<void>(),
  543. release = Promise.withResolvers<void>();
  544. clientConnectMock.mockImplementationOnce(async () => {
  545. entered.resolve();
  546. await release.promise;
  547. });
  548. const adapter = createMcpAdapter();
  549. const pool = createMcpConnectionPool({ createAdapter: () => adapter, idleGraceMs: 0 });
  550. const a = pool.acquireLease(),
  551. b = pool.acquireLease();
  552. const config = { type: "stdio" as const, command: "node", isolation: "workspace" as const };
  553. const options = { workspaceIdentity: "shared" };
  554. const abort = new AbortController();
  555. const initial = a.connectServer("demo", config, { ...options, signal: abort.signal });
  556. try {
  557. await entered.promise;
  558. abort.abort();
  559. // 租约侧取消以 reject 结束首个调用方的等待;连接本身仍在进行。
  560. await expect(initial).rejects.toThrow();
  561. expect(adapter.getToolSnapshot().demo.status.status).toBe("connecting");
  562. expect(
  563. (await b.connectServer("demo", config, { ...options, oauthAuthorizationTimeoutMs: 5 }))
  564. .status,
  565. ).toBe("connecting");
  566. let complete = false;
  567. const survivor = b.connectServer("demo", config, options).then((status) => {
  568. complete = true;
  569. return status;
  570. });
  571. await new Promise<void>((resolve) => setImmediate(resolve));
  572. expect(complete).toBe(false);
  573. release.resolve();
  574. expect((await survivor).status).toBe("connected");
  575. expect(clientConnectMock).toHaveBeenCalledOnce();
  576. } finally {
  577. release.resolve();
  578. await initial.catch(() => undefined);
  579. await pool.close();
  580. }
  581. });
  582. it("hands a notification at refresh completion to the next refresh", async () => {
  583. const adapter = createMcpAdapter();
  584. const tool = (name: string) => ({ name, inputSchema: { type: "object", properties: {} } });
  585. await adapter.connectServer("demo", { type: "stdio", command: "node" });
  586. const notify = () =>
  587. capturedClients.at(-1)!.notificationHandlers.get("notifications/tools/list_changed")!({});
  588. clientListToolsMock
  589. .mockResolvedValueOnce({ tools: [tool("first")] })
  590. .mockResolvedValueOnce({ tools: [tool("last")] });
  591. const finished = Promise.withResolvers<void>();
  592. const off = adapter.onSnapshotChanged!(() => {
  593. const name = adapter.getToolSnapshot().demo.tools?.[0]?.toolName;
  594. if (name === "first") notify();
  595. if (name === "last") finished.resolve();
  596. });
  597. try {
  598. notify();
  599. await withTimeout(finished.promise, 500, "notification lost during task handoff");
  600. expect(clientListToolsMock).toHaveBeenCalledTimes(3);
  601. } finally {
  602. off();
  603. await adapter.close();
  604. }
  605. });
  606. it.each(["subscribe", "unsubscribe"] as const)(
  607. "serializes a changed resource intent while %s is in flight",
  608. async (operation) => {
  609. const adapter = createMcpAdapter();
  610. await adapter.connectServer("demo", { type: "stdio", command: "node" });
  611. const entered = Promise.withResolvers<void>(),
  612. release = Promise.withResolvers<void>();
  613. const first = { serverName: "demo", uri: "test://resource", subscriberKey: "first" };
  614. const second = { ...first, subscriberKey: "second" };
  615. const events: string[] = [];
  616. clientSubscribeMock.mockImplementation(async () => {
  617. events.push("subscribe");
  618. return {};
  619. });
  620. clientUnsubscribeMock.mockImplementation(async () => {
  621. events.push("unsubscribe");
  622. return {};
  623. });
  624. if (operation === "unsubscribe") await adapter.subscribeResource!(first);
  625. const blocked = operation === "subscribe" ? clientSubscribeMock : clientUnsubscribeMock;
  626. blocked.mockImplementationOnce(async () => {
  627. entered.resolve();
  628. await release.promise;
  629. events.push(operation);
  630. return {};
  631. });
  632. const pending =
  633. operation === "subscribe"
  634. ? adapter.subscribeResource!(first)
  635. : adapter.unsubscribeResource!(first);
  636. try {
  637. await entered.promise;
  638. const latest =
  639. operation === "subscribe"
  640. ? adapter.unsubscribeResource!(first)
  641. : adapter.subscribeResource!(second);
  642. await new Promise<void>((resolve) => setImmediate(resolve));
  643. expect(events).toEqual(operation === "subscribe" ? [] : ["subscribe"]);
  644. release.resolve();
  645. await Promise.all([pending, latest]);
  646. expect(events).toEqual(
  647. operation === "subscribe"
  648. ? ["subscribe", "unsubscribe"]
  649. : ["subscribe", "unsubscribe", "subscribe"],
  650. );
  651. } finally {
  652. release.resolve();
  653. await pending;
  654. await adapter.close();
  655. }
  656. },
  657. );
  658. it("does not publish a discovery result after its client closed", async () => {
  659. clientListToolsMock.mockImplementationOnce(async () => {
  660. capturedClients.at(-1)!.onclose?.();
  661. return { tools: [] };
  662. });
  663. const adapter = createMcpAdapter();
  664. try {
  665. const status = await adapter.connectServer("demo", { type: "stdio", command: "node" });
  666. expect(status.status).toBe("failed");
  667. expect(adapter.appConnectionSnapshot!("demo")).toBeNull();
  668. expect(adapter.getToolSnapshot().demo.tools).toBeUndefined();
  669. } finally {
  670. await adapter.close();
  671. }
  672. });
  673. it("cancels only the initial caller wait while the shared connection keeps starting", async () => {
  674. const started = Promise.withResolvers<void>();
  675. const release = Promise.withResolvers<void>();
  676. clientConnectMock.mockImplementationOnce(async () => {
  677. started.resolve();
  678. await release.promise;
  679. });
  680. const adapter = createMcpAdapter();
  681. const controller = new AbortController();
  682. const connecting = adapter.connectServer(
  683. "demo",
  684. { type: "stdio", command: "node" },
  685. { signal: controller.signal },
  686. );
  687. try {
  688. await started.promise;
  689. controller.abort();
  690. expect((await connecting).status).toBe("connecting");
  691. release.resolve();
  692. expect(await adapter.waitForServer!("demo", { timeoutMs: 1000 })).toEqual({
  693. timedOut: false,
  694. });
  695. expect(adapter.getToolSnapshot().demo.status.status).toBe("connected");
  696. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  697. } finally {
  698. release.resolve();
  699. await adapter.close();
  700. }
  701. });
  702. it("retains pending tools through recovery attempts and clears them only on exhaustion", async () => {
  703. vi.useFakeTimers();
  704. const adapter = createMcpAdapter();
  705. const observed: Array<{ status: string; tools: number | undefined }> = [];
  706. try {
  707. clientListToolsMock.mockResolvedValueOnce({
  708. tools: [{ name: "ping", inputSchema: { type: "object" } }],
  709. } as never);
  710. await adapter.connectServer("demo", { type: "http", url: "https://mcp.example.test" });
  711. clientListToolsMock.mockRejectedValue(new Error("discovery unavailable"));
  712. adapter.onSnapshotChanged!(() => {
  713. const row = adapter.getToolSnapshot().demo;
  714. observed.push({ status: row.status.status, tools: row.tools?.length });
  715. });
  716. capturedClients.at(-1)!.onclose!();
  717. await vi.advanceTimersByTimeAsync(15_000);
  718. expect(clientConnectMock).toHaveBeenCalledTimes(6);
  719. expect(observed.at(-1)).toEqual({ status: "failed", tools: undefined });
  720. expect(observed.slice(0, -1).length).toBeGreaterThan(0);
  721. expect(
  722. observed.slice(0, -1).every((row) => row.status === "connecting" && row.tools === 1),
  723. ).toBe(true);
  724. expect(adapter.getToolSnapshot().demo.recovering).toBeUndefined();
  725. } finally {
  726. await adapter.close();
  727. vi.useRealTimers();
  728. }
  729. });
  730. it("notifies terminal failure after delayed connection cleanup, without emitting on reads", async () => {
  731. const closing = Promise.withResolvers<void>();
  732. clientListToolsMock.mockRejectedValueOnce(new Error("discovery failed"));
  733. clientCloseMock.mockImplementationOnce(() => closing.promise);
  734. const adapter = createMcpAdapter();
  735. const states: string[] = [];
  736. adapter.onSnapshotChanged!(() => {
  737. states.push(adapter.getToolSnapshot().demo?.status.status ?? "missing");
  738. });
  739. const connecting = adapter.connectServer("demo", { type: "stdio", command: "node" });
  740. await vi.waitFor(() => expect(clientCloseMock).toHaveBeenCalled());
  741. closing.resolve();
  742. await connecting;
  743. await Promise.resolve();
  744. expect(states.at(-1)).toBe("failed");
  745. const count = states.length;
  746. adapter.getToolSnapshot();
  747. await adapter.status();
  748. adapter.getToolSnapshot();
  749. await Promise.resolve();
  750. expect(states).toHaveLength(count);
  751. await adapter.close();
  752. });
  753. it("commits replacement, removal and disablement before awaiting old connection close", async () => {
  754. const adapter = createMcpAdapter();
  755. const config = { type: "stdio" as const, command: "server-a" };
  756. clientListToolsMock.mockResolvedValue({
  757. tools: [{ name: "old", inputSchema: { type: "object" } }],
  758. } as never);
  759. await adapter.connectConfiguredServers({ replaced: config, removed: config, disabled: config });
  760. const closing = Promise.withResolvers<void>();
  761. clientCloseMock.mockImplementationOnce(() => closing.promise);
  762. const pending = adapter.connectConfiguredServers({
  763. replaced: { ...config, command: "server-b" },
  764. disabled: { ...config, enabled: false },
  765. });
  766. try {
  767. const snapshot = adapter.getToolSnapshot!();
  768. expect(snapshot.replaced?.status.status).toBe("connecting");
  769. expect(snapshot.replaced?.tools).toBeUndefined();
  770. expect(snapshot.removed?.status.status).toBe("disconnected");
  771. expect(snapshot.disabled?.status.status).toBe("disabled");
  772. } finally {
  773. closing.resolve();
  774. await pending;
  775. await adapter.close();
  776. }
  777. });
  778. it.each(["disconnect", "disable"] as const)(
  779. "late %s completion cannot overwrite a newer connection",
  780. async (action) => {
  781. const adapter = createMcpAdapter();
  782. const config = { type: "stdio" as const, command: "server-a" };
  783. await adapter.connectServer("demo", config);
  784. const closing = Promise.withResolvers<void>();
  785. clientCloseMock.mockImplementationOnce(() => closing.promise);
  786. const old =
  787. action === "disconnect"
  788. ? adapter.disconnectServer("demo")
  789. : adapter.connectServer("demo", { ...config, enabled: false });
  790. try {
  791. await adapter.connectServer("demo", { ...config, command: "server-b" });
  792. closing.resolve();
  793. await old;
  794. expect(adapter.getToolSnapshot!().demo?.status.status).toBe("connected");
  795. } finally {
  796. closing.resolve();
  797. await old;
  798. await adapter.close();
  799. }
  800. },
  801. );
  802. it("authorizes once and retries a tool call that hit an OAuth error", async () => {
  803. const descriptor = {
  804. name: "oauth_ping",
  805. inputSchema: { type: "object" },
  806. annotations: { readOnlyHint: true },
  807. };
  808. clientListToolsMock.mockResolvedValue({ tools: [descriptor] } as never);
  809. const adapter = createMcpAdapter();
  810. await adapter.connectServer("runtime", {
  811. type: "http",
  812. url: "https://mcp.example.test/mcp",
  813. oauth: { type: "authorization_code" },
  814. });
  815. // 模型调用不固定定义:授权后的新连接只要仍提供该工具即可重试。
  816. clientListToolsMock.mockResolvedValue({
  817. tools: [{ ...descriptor, annotations: { readOnlyHint: false } }],
  818. } as never);
  819. clientCallToolMock
  820. .mockRejectedValueOnce(new UnauthorizedError())
  821. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  822. try {
  823. await expect(
  824. adapter.callTool({ serverName: "runtime", toolName: "oauth_ping" }),
  825. ).resolves.toMatchObject({ content: [{ text: "ok" }] });
  826. expect(authMock).toHaveBeenCalledTimes(1);
  827. expect(clientCallToolMock).toHaveBeenCalledTimes(2);
  828. } finally {
  829. await adapter.close();
  830. }
  831. });
  832. it("accepts an OAuth recovery whose status object changed after unrelated list refresh", async () => {
  833. const target = { name: "ping", inputSchema: { type: "object" } };
  834. clientListToolsMock.mockResolvedValue({ tools: [target] } as never);
  835. const adapter = createMcpAdapter();
  836. await adapter.connectServer("runtime", {
  837. type: "http",
  838. url: "https://mcp.example.test/mcp",
  839. oauth: { type: "authorization_code" },
  840. });
  841. let refreshed = false;
  842. const unsubscribe = adapter.onSnapshotChanged!(() => {
  843. if (
  844. capturedClients.length === 2 &&
  845. adapter.getToolSnapshot().runtime?.status.status === "connected" &&
  846. !refreshed
  847. ) {
  848. refreshed = true;
  849. clientListToolsMock.mockResolvedValue({
  850. tools: [target, { name: "other", inputSchema: { type: "object" } }],
  851. } as never);
  852. capturedClients.at(-1)!.notificationHandlers.get("notifications/tools/list_changed")!({});
  853. }
  854. });
  855. clientCallToolMock.mockRejectedValueOnce(new UnauthorizedError());
  856. try {
  857. await expect(
  858. adapter.callTool({ serverName: "runtime", toolName: "ping" }),
  859. ).resolves.toMatchObject({ content: [{ text: "ok" }] });
  860. expect(refreshed).toBe(true);
  861. expect(clientCallToolMock).toHaveBeenCalledTimes(2);
  862. } finally {
  863. unsubscribe();
  864. await adapter.close();
  865. }
  866. });
  867. it.each([
  868. ["a local not-connected error", "http", SdkErrorCode.NotConnected, "Not connected", 1],
  869. ["a connection-closed error", "http", SdkErrorCode.ConnectionClosed, "Connection closed", 2],
  870. [
  871. "a connection-closed code with other text",
  872. "http",
  873. SdkErrorCode.ConnectionClosed,
  874. "Not connected",
  875. 2,
  876. ],
  877. [
  878. "a stdio connection-closed error",
  879. "stdio",
  880. SdkErrorCode.ConnectionClosed,
  881. "Connection closed",
  882. 1,
  883. ],
  884. ] as const)(
  885. "retries a call once only for HTTP connection-closed errors: %s",
  886. async (_label, type, code, message, calls) => {
  887. const target = { name: "ping", inputSchema: { type: "object" } };
  888. clientListToolsMock.mockResolvedValue({ tools: [target] } as never);
  889. const adapter = createMcpAdapter();
  890. await adapter.connectServer(
  891. "demo",
  892. type === "http" ? { type, url: "https://mcp.example.test/mcp" } : { type, command: "node" },
  893. );
  894. clientCallToolMock.mockRejectedValueOnce(new SdkError(code, message));
  895. try {
  896. const call = adapter.callTool({ serverName: "demo", toolName: "ping" });
  897. if (calls === 2) await expect(call).resolves.toMatchObject({ content: [{ text: "ok" }] });
  898. else await expect(call).rejects.toThrow();
  899. expect(clientCallToolMock).toHaveBeenCalledTimes(calls);
  900. } finally {
  901. await adapter.close();
  902. }
  903. },
  904. );
  905. it("does not retry on a replaced configuration after the connection closes", async () => {
  906. clientListToolsMock.mockResolvedValue({
  907. tools: [{ name: "ping", inputSchema: { type: "object" } }],
  908. } as never);
  909. const adapter = createMcpAdapter();
  910. const entered = Promise.withResolvers<void>();
  911. const release = Promise.withResolvers<void>();
  912. clientCallToolMock.mockImplementationOnce(async () => {
  913. entered.resolve();
  914. await release.promise;
  915. throw new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed");
  916. });
  917. await adapter.connectServer("demo", { type: "http", url: "https://old.example.test/mcp" });
  918. const call = adapter.callTool({ serverName: "demo", toolName: "ping" });
  919. const observed = call.then(
  920. () => "called",
  921. () => "rejected",
  922. );
  923. try {
  924. await entered.promise;
  925. await adapter.connectServer("demo", { type: "http", url: "https://new.example.test/mcp" });
  926. const replacement = adapter.appConnectionSnapshot!("demo");
  927. release.resolve();
  928. expect(await observed).toBe("rejected");
  929. expect(adapter.appConnectionSnapshot!("demo")).toEqual(replacement);
  930. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  931. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  932. } finally {
  933. release.resolve();
  934. await observed;
  935. await adapter.close();
  936. }
  937. });
  938. it("does not replay an authorized call after its lease is revoked during OAuth recovery", async () => {
  939. const pool = createMcpConnectionPool({
  940. createAdapter: () => createMcpAdapter(),
  941. idleGraceMs: 0,
  942. });
  943. const caller = pool.acquireLease({ sessionId: "caller" });
  944. const other = pool.acquireLease({ sessionId: "other" });
  945. const config = {
  946. type: "http" as const,
  947. url: "https://mcp.example.test/mcp",
  948. oauth: { type: "authorization_code" as const },
  949. isolation: "workspace" as const,
  950. };
  951. clientListToolsMock.mockResolvedValue({
  952. tools: [{ name: "oauth_ping", inputSchema: { type: "object" } }],
  953. } as never);
  954. await caller.connectServer("demo", config);
  955. await other.connectServer("demo", config);
  956. const entered = Promise.withResolvers<void>();
  957. const authorized = Promise.withResolvers<void>();
  958. authMock.mockImplementationOnce(async () => {
  959. entered.resolve();
  960. await authorized.promise;
  961. return "AUTHORIZED";
  962. });
  963. clientCallToolMock
  964. .mockRejectedValueOnce(new UnauthorizedError())
  965. .mockResolvedValue({ content: [] });
  966. const call = caller.callTool({ serverName: "demo", toolName: "oauth_ping" });
  967. const observed = call.then(
  968. () => "called",
  969. (error) => String(error),
  970. );
  971. try {
  972. await entered.promise;
  973. await caller.connectConfiguredServers({});
  974. authorized.resolve();
  975. // 授权完成后本租约已释放:不替它重放调用,返回原授权错误。
  976. expect(await observed).toMatch(/Unauthorized/);
  977. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  978. expect(other.getToolSnapshot!()?.demo?.status.status).toBe("connected");
  979. } finally {
  980. authorized.resolve();
  981. await observed;
  982. await caller.close();
  983. await other.close();
  984. await pool.close();
  985. }
  986. });
  987. it("forwards runtime scope, session, turn, and trace context through MCP request metadata", async () => {
  988. const adapter = createMcpAdapter();
  989. await adapter.connectServer("node_repl", {
  990. command: "node",
  991. type: "stdio",
  992. });
  993. await adapter.callTool({
  994. arguments: { code: "1 + 1" },
  995. serverName: "node_repl",
  996. toolName: "js",
  997. runtimeScope: "subagent",
  998. trace: {
  999. parentSpanId: "parent-1",
  1000. sessionId: "session-1" as never,
  1001. spanId: "span-1",
  1002. traceId: "trace-1" as never,
  1003. turnId: "turn-1" as never,
  1004. },
  1005. });
  1006. expect(clientCallToolMock).toHaveBeenCalledWith(
  1007. {
  1008. arguments: { code: "1 + 1" },
  1009. name: "js",
  1010. _meta: {
  1011. "com.zcode/request-context": {
  1012. parent_span_id: "parent-1",
  1013. runtime_scope: "subagent",
  1014. session_id: "session-1",
  1015. span_id: "span-1",
  1016. trace_id: "trace-1",
  1017. turn_id: "turn-1",
  1018. },
  1019. parent_span_id: "parent-1",
  1020. runtime_scope: "subagent",
  1021. session_id: "session-1",
  1022. span_id: "span-1",
  1023. trace_id: "trace-1",
  1024. turn_id: "turn-1",
  1025. },
  1026. },
  1027. expect.objectContaining({ resetTimeoutOnProgress: true }),
  1028. );
  1029. });
  1030. it("forwards the root session of a subagent call through MCP request metadata", async () => {
  1031. const adapter = createMcpAdapter();
  1032. await adapter.connectServer("node_repl", { command: "node", type: "stdio" });
  1033. await adapter.callTool({
  1034. arguments: { code: "1 + 1" },
  1035. serverName: "node_repl",
  1036. toolName: "js",
  1037. runtimeScope: "subagent",
  1038. trace: {
  1039. rootSessionId: "session-1" as never,
  1040. sessionId: "subagent-1" as never,
  1041. traceId: "trace-1" as never,
  1042. },
  1043. });
  1044. const meta = clientCallToolMock.mock.calls.at(-1)?.[0]._meta;
  1045. expect(meta).toMatchObject({ root_session_id: "session-1", session_id: "subagent-1" });
  1046. expect(meta["com.zcode/request-context"]).toMatchObject({
  1047. root_session_id: "session-1",
  1048. session_id: "subagent-1",
  1049. });
  1050. });
  1051. it("uses the injected client version for MCP initialize", async () => {
  1052. const adapter = createMcpAdapter({ clientVersion: "9.8.7" });
  1053. await adapter.connectServer("demo", {
  1054. command: "node",
  1055. type: "stdio",
  1056. });
  1057. expect(capturedClientInfo).toEqual([
  1058. {
  1059. name: "zcode",
  1060. version: "9.8.7",
  1061. },
  1062. ]);
  1063. });
  1064. it("logs the configured negotiation policy and actual MCP protocol version", async () => {
  1065. const infoMock = vi.fn();
  1066. const logger = {
  1067. child: vi.fn(),
  1068. debug: vi.fn(),
  1069. error: vi.fn(),
  1070. info: infoMock,
  1071. warn: vi.fn(),
  1072. };
  1073. logger.child.mockReturnValue(logger);
  1074. const adapter = createMcpAdapter({
  1075. clientName: "zcode-test",
  1076. clientVersion: "9.8.7",
  1077. connectionContext: {
  1078. mcpConnectionId: "connection-session-1",
  1079. mcpIsolation: "session",
  1080. sessionId: "session-1",
  1081. workspaceKey: "workspace-1",
  1082. },
  1083. logger,
  1084. });
  1085. await adapter.connectServer("auto-modern", {
  1086. command: "node",
  1087. type: "stdio",
  1088. });
  1089. await adapter.connectServer("explicit-legacy", {
  1090. command: "node",
  1091. protocolVersion: "legacy",
  1092. type: "stdio",
  1093. });
  1094. expect(infoMock).toHaveBeenCalledWith(
  1095. "MCP server connected",
  1096. expect.objectContaining({
  1097. event: "mcp.server.connected",
  1098. mcpClientName: "zcode-test",
  1099. mcpClientVersion: "9.8.7",
  1100. mcpConnectionId: "connection-session-1",
  1101. mcpIsolation: "session",
  1102. mcpProtocolEra: "modern",
  1103. mcpProtocolVersion: "2026-07-28",
  1104. mcpServerName: "auto-modern",
  1105. mcpTransportPid: 42_424,
  1106. mcpVersionNegotiationMode: "auto",
  1107. sessionId: "session-1",
  1108. workspaceKey: "workspace-1",
  1109. }),
  1110. );
  1111. expect(infoMock).toHaveBeenCalledWith(
  1112. "MCP server connected",
  1113. expect.objectContaining({
  1114. event: "mcp.server.connected",
  1115. mcpClientName: "zcode-test",
  1116. mcpClientVersion: "9.8.7",
  1117. mcpProtocolEra: "legacy",
  1118. mcpProtocolVersion: "2025-11-25",
  1119. mcpServerName: "explicit-legacy",
  1120. mcpVersionNegotiationMode: "legacy",
  1121. }),
  1122. );
  1123. });
  1124. it("defaults ordinary MCP servers to dual-era auto while keeping explicit era pins", async () => {
  1125. const adapter = createMcpAdapter();
  1126. await adapter.connectServer("browser_use", {
  1127. command: "node",
  1128. protocolVersion: "2026-07-28",
  1129. timeoutMs: 600_000,
  1130. type: "stdio",
  1131. });
  1132. await adapter.connectServer("default-stdio", {
  1133. command: "node",
  1134. type: "stdio",
  1135. });
  1136. await adapter.connectServer("default-http", {
  1137. type: "http",
  1138. url: "https://mcp.example.test",
  1139. });
  1140. await adapter.connectServer("auto-http", {
  1141. protocolVersion: "auto",
  1142. timeoutMs: 2_000,
  1143. type: "http",
  1144. url: "https://mcp.example.test/auto",
  1145. });
  1146. await adapter.connectServer("legacy-http", {
  1147. protocolVersion: "legacy",
  1148. type: "http",
  1149. url: "https://mcp.example.test/legacy",
  1150. });
  1151. await adapter.connectServer("legacy-sse", {
  1152. type: "sse",
  1153. url: "https://mcp.example.test/sse",
  1154. });
  1155. expect(
  1156. capturedClientOptions.map((options) => ({
  1157. versionNegotiation: (options as { versionNegotiation?: unknown }).versionNegotiation,
  1158. })),
  1159. ).toEqual([
  1160. {
  1161. versionNegotiation: {
  1162. mode: { pin: "2026-07-28" },
  1163. probe: { timeoutMs: 600_000 },
  1164. },
  1165. },
  1166. { versionNegotiation: { mode: "auto", probe: { timeoutMs: 5_000 } } },
  1167. { versionNegotiation: { mode: "auto", probe: { timeoutMs: 5_000 } } },
  1168. { versionNegotiation: { mode: "auto", probe: { timeoutMs: 1_000 } } },
  1169. { versionNegotiation: { mode: "legacy" } },
  1170. { versionNegotiation: { mode: "legacy" } },
  1171. ]);
  1172. // MCP Apps:每个 client 都宣告可渲染的 UI mimeType,server 据此决定是否下发 ui 资源。
  1173. for (const options of capturedClientOptions) {
  1174. expect(options).toMatchObject({
  1175. capabilities: {
  1176. extensions: {
  1177. "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] },
  1178. },
  1179. },
  1180. });
  1181. }
  1182. });
  1183. it("preserves non-object structuredContent from MCP 2026-07-28", async () => {
  1184. clientCallToolMock.mockResolvedValue({
  1185. content: [{ type: "text", text: "ok" }],
  1186. structuredContent: ["first", 2, true],
  1187. });
  1188. const adapter = createMcpAdapter();
  1189. await adapter.connectServer("modern", {
  1190. command: "node",
  1191. protocolVersion: "2026-07-28",
  1192. type: "stdio",
  1193. });
  1194. await expect(
  1195. adapter.callTool({
  1196. serverName: "modern",
  1197. toolName: "array-result",
  1198. }),
  1199. ).resolves.toMatchObject({
  1200. structuredContent: ["first", 2, true],
  1201. });
  1202. });
  1203. it("projects server timeout onto listed MCP tool descriptors", async () => {
  1204. clientListToolsMock.mockResolvedValue({
  1205. tools: [
  1206. {
  1207. name: "long-task",
  1208. inputSchema: {
  1209. type: "object",
  1210. properties: {},
  1211. },
  1212. },
  1213. ],
  1214. });
  1215. const adapter = createMcpAdapter();
  1216. await adapter.connectServer("demo", {
  1217. command: "node",
  1218. timeoutMs: 900_000,
  1219. type: "stdio",
  1220. });
  1221. await expect(adapter.listTools()).resolves.toMatchObject([
  1222. {
  1223. serverName: "demo",
  1224. toolName: "long-task",
  1225. name: "mcp__demo__long-task",
  1226. timeoutMs: 900_000,
  1227. },
  1228. ]);
  1229. });
  1230. it("reports connecting status while an MCP server is still starting", async () => {
  1231. let resolveConnect!: () => void;
  1232. clientConnectMock.mockImplementation(
  1233. () =>
  1234. new Promise<void>((resolve) => {
  1235. resolveConnect = resolve;
  1236. }),
  1237. );
  1238. const adapter = createMcpAdapter();
  1239. const connect = adapter.connectServer("demo", {
  1240. command: "node",
  1241. type: "stdio",
  1242. });
  1243. await Promise.resolve();
  1244. await expect(adapter.status()).resolves.toMatchObject({
  1245. demo: {
  1246. status: "connecting",
  1247. transport: "stdio",
  1248. toolCount: 0,
  1249. },
  1250. });
  1251. resolveConnect();
  1252. await expect(connect).resolves.toMatchObject({
  1253. status: "connected",
  1254. toolCount: 0,
  1255. });
  1256. });
  1257. it("bounds callTool waiting for a shared startup connection without cancelling it", async () => {
  1258. let resolveConnect!: () => void;
  1259. clientConnectMock.mockImplementation(
  1260. () =>
  1261. new Promise<void>((resolve) => {
  1262. resolveConnect = resolve;
  1263. }),
  1264. );
  1265. const adapter = createMcpAdapter();
  1266. const connect = adapter.connectServer("demo", {
  1267. command: "node",
  1268. type: "stdio",
  1269. });
  1270. await Promise.resolve();
  1271. const call = adapter.callTool(
  1272. {
  1273. serverName: "demo",
  1274. toolName: "slow-start",
  1275. },
  1276. { timeoutMs: 20 },
  1277. );
  1278. try {
  1279. await expect(observePromiseWithin(call, 200)).resolves.toMatchObject({
  1280. reason: {
  1281. name: "McpTimeoutError",
  1282. },
  1283. status: "rejected",
  1284. });
  1285. await expect(adapter.status()).resolves.toMatchObject({
  1286. demo: { status: "connecting" },
  1287. });
  1288. expect(clientCallToolMock).not.toHaveBeenCalled();
  1289. } finally {
  1290. resolveConnect();
  1291. await Promise.allSettled([connect, call]);
  1292. await adapter.close();
  1293. }
  1294. await expect(adapter.status()).resolves.toEqual({});
  1295. });
  1296. it("includes sanitized recent stdio stderr when MCP server connection fails", async () => {
  1297. const debugMock = vi.fn();
  1298. const warnMock = vi.fn();
  1299. const logger = {
  1300. child: vi.fn(),
  1301. debug: debugMock,
  1302. error: vi.fn(),
  1303. info: vi.fn(),
  1304. warn: warnMock,
  1305. };
  1306. logger.child.mockReturnValue(logger);
  1307. clientConnectMock.mockImplementation(async () => {
  1308. capturedStdioStderrHandlers[0]?.(
  1309. Buffer.from(
  1310. [
  1311. "MYSQL_PASS=super-secret",
  1312. "Authorization: Bearer live-token",
  1313. "fatal: database refused connection",
  1314. ].join("\n"),
  1315. ),
  1316. );
  1317. throw new Error("MCP error -32000: Connection closed");
  1318. });
  1319. const adapter = createMcpAdapter({ logger });
  1320. await expect(
  1321. adapter.connectServer("mysql-local", {
  1322. command: "node",
  1323. type: "stdio",
  1324. }),
  1325. ).resolves.toMatchObject({
  1326. error: expect.stringContaining("fatal: database refused connection"),
  1327. status: "failed",
  1328. });
  1329. expect(debugMock).toHaveBeenCalledWith(
  1330. "MCP stdio stderr",
  1331. expect.objectContaining({
  1332. stderr: expect.stringContaining("fatal: database refused connection"),
  1333. }),
  1334. );
  1335. expect(warnMock).toHaveBeenCalledWith(
  1336. "MCP server connection failed",
  1337. expect.objectContaining({
  1338. error: "MCP error -32000: Connection closed",
  1339. event: "mcp.server.failed",
  1340. stderr: expect.stringContaining("fatal: database refused connection"),
  1341. }),
  1342. );
  1343. const warnContext = warnMock.mock.calls[0]?.[1] as { stderr?: string };
  1344. expect(warnContext.stderr).toContain("MYSQL_PASS=[Redacted]");
  1345. expect(warnContext.stderr).toContain("Authorization: Bearer [Redacted]");
  1346. expect(warnContext.stderr).not.toContain("super-secret");
  1347. expect(warnContext.stderr).not.toContain("live-token");
  1348. const status = (await adapter.status())["mysql-local"];
  1349. expect(status?.error).toContain("MCP error -32000: Connection closed");
  1350. expect(status?.error).toContain("MYSQL_PASS=[Redacted]");
  1351. expect(status?.error).not.toContain("super-secret");
  1352. expect(status?.error).not.toContain("live-token");
  1353. await adapter.close();
  1354. });
  1355. it.each([
  1356. ["python", "ModuleNotFoundError: No module named 'mcp'"],
  1357. ["node", "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'example-mcp'"],
  1358. ["path", "ENOENT: no such file or directory"],
  1359. ["permission", "PermissionError: [Errno 13] Permission denied"],
  1360. ])(
  1361. "exposes bounded sanitized %s startup evidence without changing failure kind",
  1362. async (_name, cause) => {
  1363. clientConnectMock.mockImplementation(async () => {
  1364. capturedStdioStderrHandlers[0]?.(
  1365. Buffer.from(
  1366. "noise".repeat(1_000) +
  1367. "\n\u001b[31m" +
  1368. cause +
  1369. "\u001b[0m\nAPI_TOKEN=fixture-secret\n",
  1370. ),
  1371. );
  1372. throw new Error("Connection closed");
  1373. });
  1374. const adapter = createMcpAdapter();
  1375. try {
  1376. const status = await adapter.connectServer("broken", { command: "node", type: "stdio" });
  1377. expect(status).toMatchObject({ status: "failed", failureKind: "process_start_failed" });
  1378. expect(status.error).toContain(cause);
  1379. expect(status.error).toContain("Connection closed");
  1380. expect(status.error).not.toContain("\u001b");
  1381. expect(status.error).not.toContain("fixture-secret");
  1382. expect(status.error!.length).toBeLessThanOrEqual(4_520);
  1383. } finally {
  1384. await adapter.close();
  1385. }
  1386. },
  1387. );
  1388. it("keeps HTTP failures separate from recent stdio stderr", async () => {
  1389. clientConnectMock.mockRejectedValue(new Error("network unavailable"));
  1390. const adapter = createMcpAdapter();
  1391. try {
  1392. const status = await adapter.connectServer("http-failure", {
  1393. type: "http",
  1394. url: "https://example.com/mcp",
  1395. headers: { Authorization: "Bearer fixture" },
  1396. });
  1397. expect(status.error).toBe("network unavailable");
  1398. expect(status.failureKind).toBe("network_unreachable");
  1399. } finally {
  1400. await adapter.close();
  1401. }
  1402. });
  1403. it("redacts quoted and escaped credential values before exposing stderr", async () => {
  1404. clientConnectMock.mockImplementation(async () => {
  1405. capturedStdioStderrHandlers[0]?.(
  1406. Buffer.from(
  1407. [
  1408. 'API_TOKEN="first secret with spaces"',
  1409. String.raw`VE_SPEECH_MCP_TOKEN="second escaped\" secret"`,
  1410. String.raw`{"access_token":"third escaped\" secret"}`,
  1411. "ModuleNotFoundError: No module named 'mcp'",
  1412. ].join("\n"),
  1413. ),
  1414. );
  1415. throw new Error("Connection closed");
  1416. });
  1417. const adapter = createMcpAdapter();
  1418. try {
  1419. const status = await adapter.connectServer("quoted-secret", {
  1420. command: "node",
  1421. type: "stdio",
  1422. });
  1423. expect(status.error).toContain("No module named 'mcp'");
  1424. expect(status.error).not.toContain("secret");
  1425. expect(status.error).not.toContain("escaped");
  1426. expect(status.error).not.toContain("spaces");
  1427. } finally {
  1428. await adapter.close();
  1429. }
  1430. });
  1431. it("does not leak a credential whose key name is cut by stderr tail truncation", async () => {
  1432. clientConnectMock.mockImplementation(async () => {
  1433. // 构造保留的 4000 字符尾部恰好从键名 VE_SPEECH_MCP_TOKEN 中间的 KEN 开始。
  1434. const head = "KEN=fixture-secret\nreal failure\n";
  1435. const tail = `${head}${"y".repeat(4000 - head.length - 1)}\n`;
  1436. capturedStdioStderrHandlers[0]?.(Buffer.from(`first line\nVE_SPEECH_MCP_TO${tail}`));
  1437. throw new Error("Connection closed");
  1438. });
  1439. const adapter = createMcpAdapter();
  1440. try {
  1441. const status = await adapter.connectServer("cut-key", { command: "node", type: "stdio" });
  1442. expect(status.error).toContain("real failure");
  1443. expect(status.error).not.toContain("fixture-secret");
  1444. } finally {
  1445. await adapter.close();
  1446. }
  1447. });
  1448. it("keeps stderr after a CR-only boundary when tail truncation cuts a credential key", async () => {
  1449. clientConnectMock.mockImplementation(async () => {
  1450. const tail = `KEN=fixture-secret\rreal failure\r${"y".repeat(4100)}\rreal failure`;
  1451. capturedStdioStderrHandlers[0]?.(Buffer.from(`VE_SPEECH_MCP_TO${tail}`));
  1452. throw new Error("Connection closed");
  1453. });
  1454. const adapter = createMcpAdapter();
  1455. try {
  1456. const status = await adapter.connectServer("cr-only", { command: "node", type: "stdio" });
  1457. expect(status.error).toContain("real failure");
  1458. expect(status.error).not.toContain("fixture-secret");
  1459. } finally {
  1460. await adapter.close();
  1461. }
  1462. });
  1463. it.each([" ", ",", ";", "&"])(
  1464. "fails closed when tail truncation cuts a quoted credential containing %j and no newline remains",
  1465. async (separator) => {
  1466. const warnMock = vi.fn();
  1467. const logger = {
  1468. child: vi.fn(),
  1469. debug: vi.fn(),
  1470. error: vi.fn(),
  1471. info: vi.fn(),
  1472. warn: warnMock,
  1473. };
  1474. logger.child.mockReturnValue(logger);
  1475. clientConnectMock.mockImplementation(async () => {
  1476. // 保留的 4000 字符尾部从 KEN="..." 开始且没有换行,凭证值内含分隔符。
  1477. const tail = `KEN="fixture${separator}leaked-suffix"`;
  1478. // 前缀 16 字符 + 4000 字符,保留的尾部正好从 KEN 开始。
  1479. const input = `VE_SPEECH_MCP_TO${tail}${"y".repeat(4000 - tail.length)}`;
  1480. capturedStdioStderrHandlers[0]?.(Buffer.from(input));
  1481. throw new Error("Connection closed");
  1482. });
  1483. const adapter = createMcpAdapter({ logger });
  1484. try {
  1485. const status = await adapter.connectServer("long-line", { command: "node", type: "stdio" });
  1486. expect(status.error).toContain("Connection closed");
  1487. for (const text of [status.error, JSON.stringify(warnMock.mock.calls)]) {
  1488. expect(text).not.toContain("fixture");
  1489. expect(text).not.toContain("leaked-suffix");
  1490. }
  1491. } finally {
  1492. await adapter.close();
  1493. }
  1494. },
  1495. );
  1496. it("marks the record disconnected and logs recent stderr when the transport closes unexpectedly", async () => {
  1497. const warnMock = vi.fn();
  1498. const logger = {
  1499. child: vi.fn(),
  1500. debug: vi.fn(),
  1501. error: vi.fn(),
  1502. info: vi.fn(),
  1503. warn: warnMock,
  1504. };
  1505. logger.child.mockReturnValue(logger);
  1506. const telemetryEvents: Array<{ kind: string; mcpInstanceId?: string }> = [];
  1507. const telemetry = createMcpTelemetryTracker({
  1508. idSalt: "device-a",
  1509. onEvent: (event) => telemetryEvents.push(event),
  1510. randomId: () => "mcp-instance-1",
  1511. });
  1512. telemetry.registerConnection({
  1513. connectionId: "connection-1",
  1514. isolation: "session",
  1515. serverName: "node_repl",
  1516. });
  1517. telemetry.acquireOwner({
  1518. connectionId: "connection-1",
  1519. ownerId: "lease-1",
  1520. sessionId: "session-1",
  1521. });
  1522. const adapter = createMcpAdapter({
  1523. connectionContext: {
  1524. mcpConnectionId: "connection-1",
  1525. mcpIsolation: "session",
  1526. sessionId: "session-1",
  1527. },
  1528. logger,
  1529. telemetry,
  1530. });
  1531. await adapter.connectServer("node_repl", {
  1532. command: "node",
  1533. type: "stdio",
  1534. });
  1535. capturedStdioStderrHandlers[0]?.(
  1536. Buffer.from("node_repl uncaughtException: boom from async timer\n"),
  1537. );
  1538. capturedClients.at(-1)?.onclose?.();
  1539. expect(warnMock).toHaveBeenCalledWith(
  1540. "MCP server connection lost",
  1541. expect.objectContaining({
  1542. event: "mcp.server.connection_lost",
  1543. mcpServerName: "node_repl",
  1544. mcpTransportPid: 42_424,
  1545. stderr: expect.stringContaining("boom from async timer"),
  1546. }),
  1547. );
  1548. const statuses = await adapter.status();
  1549. expect(statuses.node_repl?.status).toBe("failed");
  1550. expect(statuses.node_repl?.failureKind).toBe("unexpected_disconnect");
  1551. expect(telemetryEvents.map((event) => [event.kind, event.mcpInstanceId])).toEqual([
  1552. ["process_start", "mcp-instance-1"],
  1553. ["process_crash", "mcp-instance-1"],
  1554. ]);
  1555. });
  1556. it("does not report connection_lost when the server is closed deliberately", async () => {
  1557. const warnMock = vi.fn();
  1558. const logger = {
  1559. child: vi.fn(),
  1560. debug: vi.fn(),
  1561. error: vi.fn(),
  1562. info: vi.fn(),
  1563. warn: warnMock,
  1564. };
  1565. logger.child.mockReturnValue(logger);
  1566. const adapter = createMcpAdapter({ logger });
  1567. await adapter.connectServer("node_repl", {
  1568. command: "node",
  1569. type: "stdio",
  1570. });
  1571. await adapter.disconnectServer("node_repl");
  1572. capturedClients.at(-1)?.onclose?.();
  1573. expect(warnMock).not.toHaveBeenCalledWith("MCP server connection lost", expect.anything());
  1574. });
  1575. // Bugfix 回归:HTTP/SSE MCP 被停掉不会派发 onclose,status() 会一直停在 connected。
  1576. // 设置页刷新依赖 pingServer 把这种无声死亡暴露出来。
  1577. it("keeps the server connected when the ping succeeds", async () => {
  1578. const adapter = createMcpAdapter();
  1579. await adapter.connectServer("official_tools", {
  1580. type: "http",
  1581. url: "https://mcp.example/mcp",
  1582. });
  1583. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(true);
  1584. expect((await adapter.status()).official_tools?.status).toBe("connected");
  1585. });
  1586. it("starts shared remote recovery when the ping hits a dead transport", async () => {
  1587. const warnMock = vi.fn();
  1588. const logger = {
  1589. child: vi.fn(),
  1590. debug: vi.fn(),
  1591. error: vi.fn(),
  1592. info: vi.fn(),
  1593. warn: warnMock,
  1594. };
  1595. logger.child.mockReturnValue(logger);
  1596. const adapter = createMcpAdapter({ logger });
  1597. await adapter.connectServer("official_tools", {
  1598. type: "http",
  1599. url: "https://mcp.example/mcp",
  1600. });
  1601. // SDK 本地错误用字符串 code(REQUEST_TIMEOUT / CONNECTION_CLOSED …)。
  1602. clientPingMock.mockRejectedValue(
  1603. Object.assign(new Error("Request timed out"), { code: "REQUEST_TIMEOUT" }),
  1604. );
  1605. const recovering = Promise.withResolvers<void>();
  1606. clientConnectMock.mockImplementationOnce(() => recovering.promise);
  1607. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(false);
  1608. expect((await adapter.status()).official_tools).toMatchObject({
  1609. status: "connecting",
  1610. });
  1611. expect(warnMock).toHaveBeenCalledWith(
  1612. "MCP server ping failed",
  1613. expect.objectContaining({
  1614. event: "mcp.server.ping.failed",
  1615. mcpServerName: "official_tools",
  1616. }),
  1617. );
  1618. recovering.resolve();
  1619. await adapter.waitForServer!("official_tools", { timeoutMs: 2000 });
  1620. await adapter.close();
  1621. });
  1622. it("explicitly retries a failed stdio connection without starting background recovery", async () => {
  1623. const adapter = createMcpAdapter();
  1624. const config = { command: "node", type: "stdio" as const };
  1625. await adapter.connectServer("stdio", config);
  1626. capturedClients[0]!.onclose?.();
  1627. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  1628. expect((await adapter.status()).stdio?.status).toBe("failed");
  1629. await adapter.connectServer("stdio", config, { revalidate: true });
  1630. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  1631. expect((await adapter.status()).stdio?.status).toBe("connected");
  1632. await adapter.close();
  1633. });
  1634. // 回归:内建 node_repl 进程被外部终止后,修复前直接进入 failed,工具在下一步离开会话,
  1635. // 模型不再调用,同 workspace 的新会话也复用这条 failed 记录,没有任何重连入口。
  1636. it("restarts a built-in stdio server after an unexpected exit and keeps its catalog meanwhile", async () => {
  1637. clientListToolsMock.mockResolvedValue({
  1638. tools: [{ name: "js", inputSchema: { type: "object" } }],
  1639. } as never);
  1640. const adapter = createMcpAdapter();
  1641. try {
  1642. await adapter.connectServer("node_repl", BUILT_IN_STDIO_CONFIG);
  1643. const restart = Promise.withResolvers<void>();
  1644. clientConnectMock.mockImplementationOnce(() => restart.promise);
  1645. capturedClients.at(-1)!.onclose?.();
  1646. const restarting = adapter.getToolSnapshot!().node_repl;
  1647. expect(restarting?.status.status).toBe("connecting");
  1648. expect(restarting?.tools?.map((tool) => tool.toolName)).toEqual(["js"]);
  1649. restart.resolve();
  1650. await adapter.waitForServer!("node_repl", { timeoutMs: 1000 });
  1651. expect(adapter.getToolSnapshot!().node_repl?.status.status).toBe("connected");
  1652. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  1653. } finally {
  1654. await adapter.close();
  1655. }
  1656. });
  1657. it("gives up after five built-in stdio restart attempts and drops the retained catalog", async () => {
  1658. clientListToolsMock.mockResolvedValue({
  1659. tools: [{ name: "js", inputSchema: { type: "object" } }],
  1660. } as never);
  1661. const adapter = createMcpAdapter();
  1662. await adapter.connectServer("node_repl", BUILT_IN_STDIO_CONFIG);
  1663. const connects = clientConnectMock.mock.calls.length;
  1664. vi.useFakeTimers();
  1665. try {
  1666. clientConnectMock.mockRejectedValue(new Error("spawn failed"));
  1667. capturedClients.at(-1)!.onclose?.();
  1668. expect(adapter.getToolSnapshot!().node_repl?.status.status).toBe("connecting");
  1669. await vi.runAllTimersAsync();
  1670. expect(clientConnectMock.mock.calls.length - connects).toBe(5);
  1671. expect(adapter.getToolSnapshot!().node_repl?.status.status).toBe("failed");
  1672. expect(await adapter.listTools()).toEqual([]);
  1673. } finally {
  1674. vi.useRealTimers();
  1675. await adapter.close();
  1676. }
  1677. });
  1678. it("limits built-in stdio restarts within the restart window", async () => {
  1679. const adapter = createMcpAdapter();
  1680. vi.useFakeTimers({ toFake: ["Date"] });
  1681. try {
  1682. await adapter.connectServer("node_repl", BUILT_IN_STDIO_CONFIG);
  1683. const exitAndSettle = async () => {
  1684. capturedClients.at(-1)!.onclose?.();
  1685. await adapter.waitForServer!("node_repl", { timeoutMs: 1000 });
  1686. return adapter.getToolSnapshot!().node_repl?.status;
  1687. };
  1688. for (let restart = 0; restart < 5; restart++)
  1689. expect((await exitAndSettle())?.status).toBe("connected");
  1690. // 第 6 次退出仍在 10 分钟窗口内:不再自动重启,进入 failed(目录保留见下一个用例)。
  1691. const connects = clientConnectMock.mock.calls.length;
  1692. expect(await exitAndSettle()).toMatchObject({
  1693. status: "failed",
  1694. failureKind: "unexpected_disconnect",
  1695. });
  1696. expect(clientConnectMock.mock.calls.length).toBe(connects);
  1697. // 显式重连重新开始计数。
  1698. await adapter.connectServer("node_repl", BUILT_IN_STDIO_CONFIG, { revalidate: true });
  1699. expect((await exitAndSettle())?.status).toBe("connected");
  1700. for (let restart = 0; restart < 4; restart++) await exitAndSettle();
  1701. expect((await exitAndSettle())?.status).toBe("failed");
  1702. // 窗口过去后再次退出时允许重启。
  1703. await adapter.connectServer("node_repl", BUILT_IN_STDIO_CONFIG, { revalidate: true });
  1704. for (let restart = 0; restart < 5; restart++) await exitAndSettle();
  1705. vi.setSystemTime(Date.now() + 10 * 60_000 + 1);
  1706. expect((await exitAndSettle())?.status).toBe("connected");
  1707. } finally {
  1708. vi.useRealTimers();
  1709. await adapter.close();
  1710. }
  1711. });
  1712. // 回归:超过重启上限后修复前清空目录,工具离开会话,执行准入重连到不了;同 workspace 的新会话
  1713. // 也复用这条 failed 记录,窗口过去后仍不可用。现在保留目录,下一次执行准入重连。
  1714. it("keeps the built-in catalog after the restart limit and restarts on the next execution", async () => {
  1715. clientListToolsMock.mockResolvedValue({
  1716. tools: [{ name: "js", inputSchema: { type: "object" } }],
  1717. } as never);
  1718. const adapter = createMcpAdapter();
  1719. try {
  1720. await adapter.connectServer("node_repl", BUILT_IN_STDIO_CONFIG);
  1721. for (let exit = 0; exit < 6; exit++) {
  1722. capturedClients.at(-1)!.onclose?.();
  1723. await adapter.waitForServer!("node_repl", { timeoutMs: 1000 });
  1724. }
  1725. const limited = adapter.getToolSnapshot!().node_repl;
  1726. expect(limited?.status).toMatchObject({
  1727. status: "failed",
  1728. failureKind: "unexpected_disconnect",
  1729. });
  1730. expect(limited?.tools?.map((tool) => tool.toolName)).toEqual(["js"]);
  1731. const connects = clientConnectMock.mock.calls.length;
  1732. const restart = Promise.withResolvers<void>();
  1733. clientConnectMock.mockImplementationOnce(() => restart.promise);
  1734. const waiting = adapter.waitForServer!("node_repl", { reconnect: true, timeoutMs: 1000 });
  1735. // 重连期间目录不离开视图。
  1736. const reconnecting = adapter.getToolSnapshot!().node_repl;
  1737. expect(reconnecting?.status.status).toBe("connecting");
  1738. expect(reconnecting?.tools?.map((tool) => tool.toolName)).toEqual(["js"]);
  1739. restart.resolve();
  1740. await expect(waiting).resolves.toEqual({ timedOut: false });
  1741. expect(adapter.getToolSnapshot!().node_repl?.status.status).toBe("connected");
  1742. expect(clientConnectMock.mock.calls.length - connects).toBe(1);
  1743. } finally {
  1744. await adapter.close();
  1745. }
  1746. });
  1747. it("drops the retained built-in catalog when the execution restart fails", async () => {
  1748. clientListToolsMock.mockResolvedValue({
  1749. tools: [{ name: "js", inputSchema: { type: "object" } }],
  1750. } as never);
  1751. const adapter = createMcpAdapter();
  1752. try {
  1753. await adapter.connectServer("node_repl", BUILT_IN_STDIO_CONFIG);
  1754. for (let exit = 0; exit < 6; exit++) {
  1755. capturedClients.at(-1)!.onclose?.();
  1756. await adapter.waitForServer!("node_repl", { timeoutMs: 1000 });
  1757. }
  1758. expect(adapter.getToolSnapshot!().node_repl?.tools?.map((tool) => tool.toolName)).toEqual([
  1759. "js",
  1760. ]);
  1761. clientConnectMock.mockRejectedValueOnce(new Error("spawn failed"));
  1762. await adapter.waitForServer!("node_repl", { reconnect: true, timeoutMs: 1000 });
  1763. const row = adapter.getToolSnapshot!().node_repl;
  1764. expect(row?.status.status).toBe("failed");
  1765. expect(row?.status.failureKind).not.toBe("unexpected_disconnect");
  1766. expect(row?.tools).toBeUndefined();
  1767. } finally {
  1768. await adapter.close();
  1769. }
  1770. });
  1771. it("still drops the catalog of an ordinary stdio server after an unexpected exit", async () => {
  1772. clientListToolsMock.mockResolvedValue({
  1773. tools: [{ name: "echo", inputSchema: { type: "object" } }],
  1774. } as never);
  1775. const adapter = createMcpAdapter();
  1776. try {
  1777. await adapter.connectServer("stdio", { command: "node", type: "stdio" });
  1778. capturedClients.at(-1)!.onclose?.();
  1779. const row = adapter.getToolSnapshot!().stdio;
  1780. expect(row?.status).toMatchObject({ status: "failed", failureKind: "unexpected_disconnect" });
  1781. expect(row?.tools).toBeUndefined();
  1782. } finally {
  1783. await adapter.close();
  1784. }
  1785. });
  1786. it("treats a JSON-RPC error answer as a live connection", async () => {
  1787. const adapter = createMcpAdapter();
  1788. await adapter.connectServer("official_tools", {
  1789. type: "http",
  1790. url: "https://mcp.example/mcp",
  1791. });
  1792. // server 回了 method-not-found:请求走通了,连接是活的,不能据此拆连接。
  1793. clientPingMock.mockRejectedValue(
  1794. Object.assign(new Error("Method not found"), { code: -32_601 }),
  1795. );
  1796. await expect(adapter.pingServer?.("official_tools")).resolves.toBe(true);
  1797. expect((await adapter.status()).official_tools?.status).toBe("connected");
  1798. });
  1799. it("reports an unknown server as not alive", async () => {
  1800. const adapter = createMcpAdapter();
  1801. await expect(adapter.pingServer?.("missing")).resolves.toBe(false);
  1802. });
  1803. it("does not reconnect a replaced configuration after its health probe fails", async () => {
  1804. const adapter = createMcpAdapter();
  1805. const config = { type: "http" as const, url: "https://mcp.example/old" };
  1806. await adapter.connectServer("docs", config);
  1807. const probe = Promise.withResolvers<Record<string, never>>();
  1808. const probing = Promise.withResolvers<void>();
  1809. clientPingMock.mockImplementationOnce(() => {
  1810. probing.resolve();
  1811. return probe.promise;
  1812. });
  1813. const refresh = adapter.connectServer("docs", config, { revalidate: true });
  1814. await probing.promise;
  1815. await adapter.connectServer("docs", { ...config, url: "https://mcp.example/new" });
  1816. probe.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed"));
  1817. await refresh;
  1818. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  1819. expect(capturedHttpOptions).toHaveLength(2);
  1820. expect((await adapter.status()).docs?.status).toBe("connected");
  1821. await adapter.close();
  1822. });
  1823. it("does not retry a stdio call whose transport reports not connected", async () => {
  1824. const adapter = createMcpAdapter();
  1825. await adapter.connectServer("node_repl", {
  1826. command: "node",
  1827. type: "stdio",
  1828. });
  1829. clientCallToolMock.mockRejectedValueOnce(new Error("Not connected"));
  1830. // 进程死亡由 onclose 进入 failed,下一次调用先重连;本次调用不重发。
  1831. await expect(
  1832. adapter.callTool({
  1833. arguments: { code: "1 + 1" },
  1834. serverName: "node_repl",
  1835. toolName: "js",
  1836. }),
  1837. ).rejects.toThrow(/Not connected/);
  1838. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  1839. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  1840. });
  1841. it("reconnects before calling when the record was already marked disconnected", async () => {
  1842. const adapter = createMcpAdapter();
  1843. await adapter.connectServer("node_repl", {
  1844. command: "node",
  1845. type: "stdio",
  1846. });
  1847. capturedClients.at(-1)?.onclose?.();
  1848. expect((await adapter.status()).node_repl?.status).toBe("failed");
  1849. const result = await adapter.callTool({
  1850. arguments: { code: "1 + 1" },
  1851. serverName: "node_repl",
  1852. toolName: "js",
  1853. });
  1854. expect(result.content).toEqual([{ type: "text", text: "ok" }]);
  1855. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  1856. expect((await adapter.status()).node_repl?.status).toBe("connected");
  1857. });
  1858. it("surfaces the original error when reconnection also fails", async () => {
  1859. const adapter = createMcpAdapter();
  1860. await adapter.connectServer("node_repl", {
  1861. command: "node",
  1862. type: "stdio",
  1863. });
  1864. clientCallToolMock.mockRejectedValue(new Error("Not connected"));
  1865. clientConnectMock.mockRejectedValue(new Error("spawn ENOENT"));
  1866. await expect(
  1867. adapter.callTool({
  1868. arguments: { code: "1 + 1" },
  1869. serverName: "node_repl",
  1870. toolName: "js",
  1871. }),
  1872. ).rejects.toThrow(/Not connected/);
  1873. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  1874. });
  1875. it("keeps transport error codes separate from the connection failure classification", async () => {
  1876. const adapter = createMcpAdapter();
  1877. clientConnectMock.mockRejectedValue(
  1878. Object.assign(new Error("Connection refused"), { cause: { code: "ECONNREFUSED" } }),
  1879. );
  1880. const status = await adapter.connectServer("diagnostic", { command: "node", type: "stdio" });
  1881. expect(status).toMatchObject({ status: "failed", errorCode: "ECONNREFUSED" });
  1882. expect(status.failureKind).not.toBe("ECONNREFUSED");
  1883. await adapter.close();
  1884. });
  1885. it("injects unified network env into stdio MCP transports", async () => {
  1886. const adapter = createMcpAdapter({
  1887. env: {
  1888. PATH: dirname(process.execPath),
  1889. ZCODE_AGENT_CA_CERT: "/tmp/root-ca.pem",
  1890. },
  1891. network: {
  1892. httpProxy: "127.0.0.1:8888",
  1893. noProxy: "localhost,127.0.0.1",
  1894. },
  1895. });
  1896. await adapter.connectServer("demo", {
  1897. command: "node",
  1898. env: {
  1899. MCP_TOKEN: "secret",
  1900. },
  1901. type: "stdio",
  1902. });
  1903. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  1904. expect(options.env).toMatchObject({
  1905. ALL_PROXY: "http://127.0.0.1:8888",
  1906. CURL_CA_BUNDLE: "/tmp/root-ca.pem",
  1907. GIT_SSL_CAINFO: "/tmp/root-ca.pem",
  1908. HTTPS_PROXY: "http://127.0.0.1:8888",
  1909. HTTP_PROXY: "http://127.0.0.1:8888",
  1910. MCP_TOKEN: "secret",
  1911. NODE_EXTRA_CA_CERTS: "/tmp/root-ca.pem",
  1912. NO_PROXY: "localhost,127.0.0.1",
  1913. // MCP 会补齐 Node 目录;本测试使用已含 Node 的 PATH,避免依赖测试机的 /bin。
  1914. PATH: dirname(process.execPath),
  1915. REQUESTS_CA_BUNDLE: "/tmp/root-ca.pem",
  1916. SSL_CERT_FILE: "/tmp/root-ca.pem",
  1917. all_proxy: "http://127.0.0.1:8888",
  1918. http_proxy: "http://127.0.0.1:8888",
  1919. https_proxy: "http://127.0.0.1:8888",
  1920. no_proxy: "localhost,127.0.0.1",
  1921. });
  1922. });
  1923. it("appends the injected node fallback after the server env", async () => {
  1924. const resolve = vi.fn(async () => ({
  1925. binDir: "/fallback/bin",
  1926. env: { ZCODE_NODE_FALLBACK_EXEC_PATH: "/electron" },
  1927. }));
  1928. const adapter = createMcpAdapter({
  1929. env: { PATH: dirname(process.execPath) },
  1930. nodeFallback: { resolve },
  1931. });
  1932. await adapter.connectServer("demo", {
  1933. command: "node",
  1934. // 插件自带 PATH 会整体替换宿主 PATH;fallback 仍须追加在它后面。
  1935. env: { PATH: "/plugin/bin" },
  1936. type: "stdio",
  1937. });
  1938. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  1939. expect(options.env?.PATH).toBe(["/plugin/bin", "/fallback/bin"].join(delimiter));
  1940. expect(options.env?.ZCODE_NODE_FALLBACK_EXEC_PATH).toBe("/electron");
  1941. expect(resolve).toHaveBeenCalledTimes(1);
  1942. });
  1943. it("restores captured user network env into stdio MCP transports", async () => {
  1944. const adapter = createMcpAdapter({
  1945. env: {
  1946. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  1947. NODE_EXTRA_CA_CERTS: "/tmp/user-ca.pem",
  1948. http_proxy: "http://user-proxy:8080",
  1949. }),
  1950. PATH: dirname(process.execPath),
  1951. },
  1952. network: {},
  1953. });
  1954. await adapter.connectServer("demo", {
  1955. command: "node",
  1956. type: "stdio",
  1957. });
  1958. const options = capturedStdioOptions[0] as { env?: Record<string, string> };
  1959. expect(options.env).toMatchObject({
  1960. NODE_EXTRA_CA_CERTS: "/tmp/user-ca.pem",
  1961. PATH: dirname(process.execPath),
  1962. http_proxy: "http://user-proxy:8080",
  1963. });
  1964. expect(options.env?.[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
  1965. });
  1966. it("passes proxy-aware fetch into HTTP and SSE MCP transports", async () => {
  1967. const adapter = createMcpAdapter({
  1968. env: {
  1969. ZCODE_HTTP_PROXY: "http://127.0.0.1:8888",
  1970. },
  1971. network: {},
  1972. });
  1973. await adapter.connectServer("http-demo", {
  1974. type: "http",
  1975. url: "https://mcp.example.test",
  1976. });
  1977. await adapter.connectServer("sse-demo", {
  1978. type: "sse",
  1979. url: "https://mcp.example.test/sse",
  1980. });
  1981. expect(capturedHttpOptions[0]).toMatchObject({
  1982. fetch: expect.any(Function),
  1983. });
  1984. expect(capturedSseOptions[0]).toMatchObject({
  1985. fetch: expect.any(Function),
  1986. });
  1987. await adapter.close();
  1988. });
  1989. it("passes a pure token AuthProvider into bare HTTP and SSE MCP transports", async () => {
  1990. const adapter = createMcpAdapter();
  1991. await adapter.connectServer("http-demo", {
  1992. type: "http",
  1993. url: "https://mcp.example.test",
  1994. });
  1995. await adapter.connectServer("sse-demo", {
  1996. type: "sse",
  1997. url: "https://mcp.example.test/sse",
  1998. });
  1999. const providers = [
  2000. (capturedHttpOptions[0] as { authProvider?: Record<string, unknown> }).authProvider,
  2001. (capturedSseOptions[0] as { authProvider?: Record<string, unknown> }).authProvider,
  2002. ];
  2003. for (const provider of providers) {
  2004. expect(provider).toBeDefined();
  2005. // 修复原因(根因 1):运行期只能是纯 AuthProvider。SDK 的 `isOAuthClientProvider()` 判定
  2006. // 依赖 `clientInformation`/`tokens` 等方法是否存在;一旦被识别为 OAuthClientProvider,
  2007. // transport 就会通过 `adaptOAuthProvider` 包裹它,401 走 SDK 的 `auth()`,绕过我们的
  2008. // refresh 单飞锁,rotation 竞态立刻复发。同时它还会带来 discovery / DCR / callback listener。
  2009. expect(typeof provider?.token).toBe("function");
  2010. expect(typeof provider?.onUnauthorized).toBe("function");
  2011. expect(provider?.clientInformation).toBeUndefined();
  2012. expect(provider?.tokens).toBeUndefined();
  2013. expect(provider?.saveTokens).toBeUndefined();
  2014. expect(provider?.clientMetadata).toBeUndefined();
  2015. expect(provider?.redirectToAuthorization).toBeUndefined();
  2016. expect(provider?.saveCodeVerifier).toBeUndefined();
  2017. }
  2018. await adapter.close();
  2019. });
  2020. it("does not attach implicit OAuth provider when HTTP MCP has an Authorization header", async () => {
  2021. const adapter = createMcpAdapter();
  2022. await adapter.connectServer("manual-token", {
  2023. type: "http",
  2024. url: "https://mcp.example.test",
  2025. headers: {
  2026. Authorization: "Bearer user-token",
  2027. },
  2028. });
  2029. expect((capturedHttpOptions[0] as { authProvider?: unknown }).authProvider).toBeUndefined();
  2030. await adapter.close();
  2031. });
  2032. it("passes OAuth client credentials providers into HTTP and SSE MCP transports", async () => {
  2033. const adapter = createMcpAdapter({
  2034. clientName: "zcode-test",
  2035. });
  2036. await adapter.connectServer("http-demo", {
  2037. type: "http",
  2038. url: "https://mcp.example.test",
  2039. headers: {
  2040. "X-ZCode": "1",
  2041. },
  2042. oauth: {
  2043. type: "client_credentials",
  2044. clientId: "http-client",
  2045. clientSecret: "http-secret",
  2046. scope: "mcp:tools",
  2047. },
  2048. });
  2049. await adapter.connectServer("sse-demo", {
  2050. type: "sse",
  2051. url: "https://mcp.example.test/sse",
  2052. oauth: {
  2053. type: "client_credentials",
  2054. clientId: "sse-client",
  2055. clientSecret: "sse-secret",
  2056. },
  2057. });
  2058. const httpOptions = capturedHttpOptions[0] as {
  2059. authProvider?: {
  2060. clientInformation(): { client_id: string; client_secret?: string };
  2061. clientMetadata: {
  2062. client_name?: string;
  2063. grant_types?: string[];
  2064. scope?: string;
  2065. };
  2066. };
  2067. requestInit?: { headers?: Record<string, string> };
  2068. };
  2069. const sseOptions = capturedSseOptions[0] as {
  2070. authProvider?: {
  2071. clientInformation(): { client_id: string; client_secret?: string };
  2072. clientMetadata: { client_name?: string; grant_types?: string[] };
  2073. };
  2074. };
  2075. expect(httpOptions.requestInit?.headers).toEqual({ "X-ZCode": "1" });
  2076. expect(httpOptions.authProvider?.clientInformation()).toEqual({
  2077. client_id: "http-client",
  2078. client_secret: "http-secret",
  2079. });
  2080. expect(httpOptions.authProvider?.clientMetadata).toMatchObject({
  2081. client_name: "zcode-test-http-demo",
  2082. grant_types: ["client_credentials"],
  2083. scope: "mcp:tools",
  2084. });
  2085. expect(sseOptions.authProvider?.clientInformation()).toEqual({
  2086. client_id: "sse-client",
  2087. client_secret: "sse-secret",
  2088. });
  2089. expect(sseOptions.authProvider?.clientMetadata).toMatchObject({
  2090. client_name: "zcode-test-sse-demo",
  2091. grant_types: ["client_credentials"],
  2092. });
  2093. });
  2094. it("exposes pending OAuth authorization URL through server status", async () => {
  2095. const { release: resolveConnect } = stubInteractiveAuthorization(
  2096. "https://auth.example.test/authorize?state=state_test",
  2097. );
  2098. const adapter = createMcpAdapter();
  2099. const connect = adapter.connectServer("notion", {
  2100. type: "http",
  2101. url: "https://mcp.example.test/mcp",
  2102. oauth: {
  2103. type: "authorization_code",
  2104. clientName: "ZCode",
  2105. },
  2106. });
  2107. let authorizationUrl: string | undefined;
  2108. for (let attempt = 0; attempt < 20; attempt += 1) {
  2109. const status = await adapter.status();
  2110. authorizationUrl = status.notion?.authorization?.authorizationUrl;
  2111. if (authorizationUrl) break;
  2112. await new Promise((resolve) => setTimeout(resolve, 10));
  2113. }
  2114. expect(authorizationUrl).toBe("https://auth.example.test/authorize?state=state_test");
  2115. resolveConnect();
  2116. await expect(connect).resolves.toMatchObject({
  2117. status: "connected",
  2118. toolCount: 0,
  2119. });
  2120. await adapter.close();
  2121. });
  2122. it("reuses an unchanged configured connection while OAuth authorization is pending", async () => {
  2123. const { release: resolveConnect } = stubInteractiveAuthorization(
  2124. "https://auth.example.test/authorize?state=stable_state",
  2125. );
  2126. const adapter = createMcpAdapter();
  2127. const firstConnect = adapter.connectConfiguredServers({
  2128. notion: {
  2129. type: "http",
  2130. url: "https://mcp.example.test/mcp",
  2131. oauth: {
  2132. type: "authorization_code",
  2133. clientName: "ZCode",
  2134. },
  2135. },
  2136. });
  2137. let authorizationUrl: string | undefined;
  2138. for (let attempt = 0; attempt < 20; attempt += 1) {
  2139. const status = await adapter.status();
  2140. authorizationUrl = status.notion?.authorization?.authorizationUrl;
  2141. if (authorizationUrl) break;
  2142. await new Promise((resolve) => setTimeout(resolve, 10));
  2143. }
  2144. const secondConnect = adapter.connectConfiguredServers({
  2145. notion: {
  2146. type: "http",
  2147. url: "https://mcp.example.test/mcp",
  2148. oauth: {
  2149. type: "authorization_code",
  2150. clientName: "ZCode",
  2151. },
  2152. },
  2153. });
  2154. await Promise.resolve();
  2155. expect(authorizationUrl).toBe("https://auth.example.test/authorize?state=stable_state");
  2156. await expect(
  2157. adapter.connectServer(
  2158. "notion",
  2159. {
  2160. type: "http",
  2161. url: "https://mcp.example.test/mcp",
  2162. oauth: { type: "authorization_code", clientName: "ZCode" },
  2163. },
  2164. { revalidate: true },
  2165. ),
  2166. ).resolves.toMatchObject({
  2167. status: "connecting",
  2168. authorization: { authorizationUrl },
  2169. });
  2170. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  2171. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  2172. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  2173. expect(capturedHttpOptions).toHaveLength(1);
  2174. await expect(adapter.status()).resolves.toMatchObject({
  2175. notion: {
  2176. authorization: {
  2177. authorizationUrl: "https://auth.example.test/authorize?state=stable_state",
  2178. },
  2179. status: "connecting",
  2180. },
  2181. });
  2182. resolveConnect();
  2183. await expect(Promise.all([firstConnect, secondConnect])).resolves.toMatchObject([
  2184. { statuses: { notion: { status: "connected" } } },
  2185. { statuses: { notion: { status: "connected" } } },
  2186. ]);
  2187. await adapter.close();
  2188. });
  2189. it("keeps a reused OAuth connection alive when a bounded caller times out", async () => {
  2190. const { release: resolveConnect } = stubInteractiveAuthorization(
  2191. "https://auth.example.test/authorize?state=shared_timeout_state",
  2192. );
  2193. const adapter = createMcpAdapter();
  2194. const servers = {
  2195. notion: {
  2196. type: "http" as const,
  2197. url: "https://mcp.example.test/mcp",
  2198. oauth: {
  2199. type: "authorization_code" as const,
  2200. clientName: "ZCode",
  2201. },
  2202. },
  2203. };
  2204. const settingsConnect = adapter.connectConfiguredServers(servers);
  2205. for (let attempt = 0; attempt < 20; attempt += 1) {
  2206. const status = await adapter.status();
  2207. if (status.notion?.authorization?.authorizationUrl) break;
  2208. await new Promise((resolve) => setTimeout(resolve, 10));
  2209. }
  2210. const sessionConnect = await adapter.connectConfiguredServers(servers, {
  2211. oauthAuthorizationTimeoutMs: 20,
  2212. });
  2213. expect(sessionConnect.statuses.notion).toMatchObject({
  2214. authorization: {
  2215. authorizationUrl: "https://auth.example.test/authorize?state=shared_timeout_state",
  2216. },
  2217. status: "connecting",
  2218. });
  2219. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  2220. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  2221. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  2222. expect(capturedHttpOptions).toHaveLength(1);
  2223. resolveConnect();
  2224. await expect(settingsConnect).resolves.toMatchObject({
  2225. statuses: { notion: { status: "connected" } },
  2226. });
  2227. await adapter.close();
  2228. });
  2229. it("only cancels the caller waiter when a reused OAuth connection is aborted", async () => {
  2230. const { release: resolveConnect } = stubInteractiveAuthorization(
  2231. "https://auth.example.test/authorize?state=shared_abort_state",
  2232. );
  2233. const adapter = createMcpAdapter();
  2234. const servers = {
  2235. notion: {
  2236. type: "http" as const,
  2237. url: "https://mcp.example.test/mcp",
  2238. oauth: {
  2239. type: "authorization_code" as const,
  2240. clientName: "ZCode",
  2241. },
  2242. },
  2243. };
  2244. const settingsConnect = adapter.connectConfiguredServers(servers);
  2245. for (let attempt = 0; attempt < 20; attempt += 1) {
  2246. const status = await adapter.status();
  2247. if (status.notion?.authorization?.authorizationUrl) break;
  2248. await new Promise((resolve) => setTimeout(resolve, 10));
  2249. }
  2250. const abortController = new AbortController();
  2251. const sessionConnect = adapter.connectConfiguredServers(servers, {
  2252. signal: abortController.signal,
  2253. });
  2254. abortController.abort(new Error("session stopped"));
  2255. await expect(sessionConnect).resolves.toMatchObject({
  2256. statuses: {
  2257. notion: {
  2258. authorization: {
  2259. authorizationUrl: "https://auth.example.test/authorize?state=shared_abort_state",
  2260. },
  2261. status: "connecting",
  2262. },
  2263. },
  2264. });
  2265. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  2266. // Phase 1 的探测 transport 在进入 Phase 2 前一定会被关闭(negotiation 失败后不可复用),
  2267. // 所以这里断言的是「第二个 caller 没有另起一条连接」,而不是 transport 从未关闭。
  2268. expect(capturedHttpOptions).toHaveLength(1);
  2269. resolveConnect();
  2270. await expect(settingsConnect).resolves.toMatchObject({
  2271. statuses: { notion: { status: "connected" } },
  2272. });
  2273. await adapter.close();
  2274. });
  2275. it("treats per-connect OAuth authorization timeout as a caller budget, not a transaction kill", async () => {
  2276. let startAuthorization!: () => void;
  2277. const beforeAuthorization = new Promise<void>((resolve) => {
  2278. startAuthorization = resolve;
  2279. });
  2280. const { release, ready } = stubInteractiveAuthorization(
  2281. "https://auth.example.test/authorize?state=state_test",
  2282. beforeAuthorization,
  2283. );
  2284. const adapter = createMcpAdapter();
  2285. const startedAt = Date.now();
  2286. try {
  2287. const status = await adapter.connectServer(
  2288. "notion",
  2289. {
  2290. type: "http",
  2291. url: "https://mcp.example.test/mcp",
  2292. timeoutMs: 2_000,
  2293. oauth: { type: "authorization_code", clientName: "ZCode" },
  2294. },
  2295. { oauthAuthorizationTimeoutMs: 20 },
  2296. );
  2297. // URL 发布含异步存储,不能假定它比 20ms caller 预算更快;事务应在 caller 返回后继续。
  2298. expect(status).toMatchObject({ status: "connecting" });
  2299. expect(status.authorization).toBeUndefined();
  2300. expect(Date.now() - startedAt).toBeLessThan(1_000);
  2301. expect(transportFinishAuthMock).not.toHaveBeenCalled();
  2302. startAuthorization();
  2303. await ready;
  2304. await expect(adapter.status()).resolves.toMatchObject({
  2305. notion: {
  2306. authorization: {
  2307. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  2308. },
  2309. status: "connecting",
  2310. },
  2311. });
  2312. release();
  2313. await vi.waitFor(async () => {
  2314. expect(await adapter.status()).toMatchObject({ notion: { status: "connected" } });
  2315. });
  2316. } finally {
  2317. startAuthorization();
  2318. release();
  2319. await adapter.close();
  2320. }
  2321. });
  2322. it("keeps runtime OAuth recovery alive after the triggering caller times out", async () => {
  2323. let startAuthorization!: () => void;
  2324. const beforeAuthorization = new Promise<void>((resolve) => {
  2325. startAuthorization = resolve;
  2326. });
  2327. let markReady!: () => void;
  2328. const ready = new Promise<void>((resolve) => {
  2329. markReady = resolve;
  2330. });
  2331. let releaseAuthorization!: () => void;
  2332. const authorizationGate = new Promise<void>((resolve) => {
  2333. releaseAuthorization = resolve;
  2334. });
  2335. authMock.mockImplementation(async (provider: unknown) => {
  2336. const interactiveProvider = provider as {
  2337. redirectToAuthorization(url: URL): Promise<void>;
  2338. state(): Promise<string>;
  2339. };
  2340. const authorizationUrl = new URL("https://auth.example.test/authorize");
  2341. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  2342. await beforeAuthorization;
  2343. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  2344. markReady();
  2345. await authorizationGate;
  2346. return "AUTHORIZED" as const;
  2347. });
  2348. clientCallToolMock
  2349. .mockRejectedValueOnce(new UnauthorizedError())
  2350. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  2351. const adapter = createMcpAdapter();
  2352. await adapter.connectServer("runtime", {
  2353. oauth: {
  2354. type: "authorization_code",
  2355. },
  2356. type: "http",
  2357. url: "https://mcp.example.test/mcp",
  2358. });
  2359. const call = adapter.callTool(
  2360. {
  2361. serverName: "runtime",
  2362. toolName: "oauth_ping",
  2363. },
  2364. { timeoutMs: 20 },
  2365. );
  2366. try {
  2367. await expect(observePromiseWithin(call, 200)).resolves.toMatchObject({
  2368. reason: {
  2369. name: "McpTimeoutError",
  2370. },
  2371. status: "rejected",
  2372. });
  2373. // 显式让 caller 先超时,再发布 URL,避免靠机器负载决定断言先后。
  2374. startAuthorization();
  2375. await ready;
  2376. await expect(adapter.status()).resolves.toMatchObject({
  2377. runtime: {
  2378. authorization: {
  2379. authorizationUrl: expect.stringContaining("https://auth.example.test/authorize"),
  2380. },
  2381. status: "connecting",
  2382. },
  2383. });
  2384. releaseAuthorization();
  2385. for (let attempt = 0; attempt < 50; attempt += 1) {
  2386. const status = await adapter.status();
  2387. if (status.runtime?.status === "connected") break;
  2388. await new Promise((resolve) => setTimeout(resolve, 10));
  2389. }
  2390. await expect(adapter.status()).resolves.toMatchObject({
  2391. runtime: { status: "connected" },
  2392. });
  2393. await expect(
  2394. adapter.callTool(
  2395. {
  2396. serverName: "runtime",
  2397. toolName: "oauth_ping",
  2398. },
  2399. { timeoutMs: 200 },
  2400. ),
  2401. ).resolves.toMatchObject({
  2402. content: [{ text: "ok", type: "text" }],
  2403. });
  2404. expect(authMock).toHaveBeenCalledTimes(1);
  2405. // 原 caller 已经超时,后台 recovery 只负责重连;不会替超时 caller 再执行工具。
  2406. expect(clientCallToolMock).toHaveBeenCalledTimes(2);
  2407. } finally {
  2408. startAuthorization();
  2409. releaseAuthorization();
  2410. await Promise.allSettled([call]);
  2411. await adapter.close();
  2412. }
  2413. });
  2414. it("shares one runtime OAuth recovery across concurrent tool callers", async () => {
  2415. let releaseAuthorization!: () => void;
  2416. const authorizationGate = new Promise<void>((resolve) => {
  2417. releaseAuthorization = resolve;
  2418. });
  2419. authMock.mockImplementation(async (provider: unknown) => {
  2420. const interactiveProvider = provider as {
  2421. redirectToAuthorization(url: URL): Promise<void>;
  2422. state(): Promise<string>;
  2423. };
  2424. const authorizationUrl = new URL("https://auth.example.test/authorize");
  2425. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  2426. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  2427. await authorizationGate;
  2428. return "AUTHORIZED" as const;
  2429. });
  2430. clientCallToolMock
  2431. .mockRejectedValueOnce(new UnauthorizedError())
  2432. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  2433. clientListToolsMock.mockResolvedValue({
  2434. tools: [{ name: "oauth_ping", inputSchema: { type: "object" } }],
  2435. } as never);
  2436. const adapter = createMcpAdapter();
  2437. await adapter.connectServer("runtime", {
  2438. oauth: {
  2439. type: "authorization_code",
  2440. },
  2441. type: "http",
  2442. url: "https://mcp.example.test/mcp",
  2443. });
  2444. const firstCall = adapter.callTool(
  2445. {
  2446. serverName: "runtime",
  2447. toolName: "oauth_ping",
  2448. },
  2449. { timeoutMs: 2_000 },
  2450. );
  2451. // 立即挂上处理:触发授权的调用在链接发布时就会 reject,晚挂会被记为未处理 rejection。
  2452. const firstOutcome = firstCall.then(
  2453. () => "resolved",
  2454. (error: unknown) => error,
  2455. );
  2456. try {
  2457. for (let attempt = 0; attempt < 50; attempt += 1) {
  2458. const status = await adapter.status();
  2459. if (status.runtime?.authorization?.authorizationUrl) break;
  2460. await new Promise((resolve) => setTimeout(resolve, 10));
  2461. }
  2462. await expect(adapter.status()).resolves.toMatchObject({
  2463. runtime: {
  2464. authorization: {
  2465. authorizationUrl: expect.stringContaining("https://auth.example.test/authorize"),
  2466. },
  2467. status: "connecting",
  2468. },
  2469. });
  2470. // 触发授权的调用在链接发布后以原始错误结束,由 core 改写为 needs-auth 文本。
  2471. expect(String(await firstOutcome)).toMatch(/Unauthorized/);
  2472. const secondCall = adapter.callTool(
  2473. {
  2474. serverName: "runtime",
  2475. toolName: "oauth_ping",
  2476. },
  2477. { timeoutMs: 2_000 },
  2478. );
  2479. await Promise.resolve();
  2480. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  2481. releaseAuthorization();
  2482. await expect(secondCall).resolves.toMatchObject({
  2483. content: [{ text: "ok", type: "text" }],
  2484. });
  2485. expect(authMock).toHaveBeenCalledTimes(1);
  2486. // 第一次认证失败 + second caller 等到同一轮授权完成后的首次实际调用;不另起授权。
  2487. expect(clientCallToolMock).toHaveBeenCalledTimes(2);
  2488. await expect(adapter.status()).resolves.toMatchObject({
  2489. runtime: { status: "connected" },
  2490. });
  2491. } finally {
  2492. releaseAuthorization();
  2493. await Promise.allSettled([firstCall]);
  2494. await adapter.close();
  2495. }
  2496. });
  2497. it("does not let a caller abort close the shared runtime OAuth callback listener", async () => {
  2498. let authorizationContext:
  2499. | {
  2500. authorizationUrl: string;
  2501. redirectUrl: string;
  2502. }
  2503. | undefined;
  2504. // 链接发布后触发调用会立即结束;在发布前中止调用,才能覆盖"调用方中止不关闭共享监听"。
  2505. const entered = Promise.withResolvers<void>();
  2506. const publish = Promise.withResolvers<void>();
  2507. authMock.mockImplementation(
  2508. async (provider: unknown, options?: { authorizationCode?: string }) => {
  2509. if (options?.authorizationCode) return "AUTHORIZED" as const;
  2510. entered.resolve();
  2511. await publish.promise;
  2512. const interactiveProvider = provider as {
  2513. redirectToAuthorization(url: URL): Promise<void>;
  2514. state(): Promise<string>;
  2515. };
  2516. const authorizationUrl = new URL("https://auth.example.test/authorize");
  2517. authorizationUrl.searchParams.set("state", await interactiveProvider.state());
  2518. await interactiveProvider.redirectToAuthorization(authorizationUrl);
  2519. return "REDIRECT" as never;
  2520. },
  2521. );
  2522. clientCallToolMock
  2523. .mockRejectedValueOnce(new UnauthorizedError())
  2524. .mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
  2525. const adapter = createMcpAdapter({
  2526. mcpOAuth: {
  2527. onAuthorizationRequired: async (context) => {
  2528. authorizationContext = context;
  2529. },
  2530. },
  2531. });
  2532. await adapter.connectServer("runtime", {
  2533. oauth: {
  2534. type: "authorization_code",
  2535. },
  2536. type: "http",
  2537. url: "https://mcp.example.test/mcp",
  2538. });
  2539. const abortController = new AbortController();
  2540. const call = adapter.callTool(
  2541. {
  2542. serverName: "runtime",
  2543. toolName: "oauth_ping",
  2544. },
  2545. {
  2546. signal: abortController.signal,
  2547. timeoutMs: 2_000,
  2548. },
  2549. );
  2550. try {
  2551. await entered.promise;
  2552. abortController.abort(new Error("caller stopped"));
  2553. await expect(observePromiseWithin(call, 200)).resolves.toMatchObject({
  2554. reason: {
  2555. message: "caller stopped",
  2556. },
  2557. status: "rejected",
  2558. });
  2559. publish.resolve();
  2560. for (let attempt = 0; attempt < 50; attempt += 1) {
  2561. if (authorizationContext) break;
  2562. await new Promise((resolve) => setTimeout(resolve, 10));
  2563. }
  2564. expect(authorizationContext).toBeDefined();
  2565. const callbackUrl = new URL(authorizationContext!.redirectUrl);
  2566. callbackUrl.searchParams.set("code", "authorized-after-caller-abort");
  2567. callbackUrl.searchParams.set(
  2568. "state",
  2569. new URL(authorizationContext!.authorizationUrl).searchParams.get("state") ?? "",
  2570. );
  2571. await expect(fetch(callbackUrl)).resolves.toMatchObject({ ok: true });
  2572. for (let attempt = 0; attempt < 50; attempt += 1) {
  2573. const status = await adapter.status();
  2574. if (status.runtime?.status === "connected") break;
  2575. await new Promise((resolve) => setTimeout(resolve, 10));
  2576. }
  2577. await expect(adapter.status()).resolves.toMatchObject({
  2578. runtime: { status: "connected" },
  2579. });
  2580. expect(authMock).toHaveBeenCalledTimes(2);
  2581. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  2582. } finally {
  2583. publish.resolve();
  2584. await Promise.allSettled([call]);
  2585. await adapter.close();
  2586. }
  2587. });
  2588. describe("tool-call authorization", () => {
  2589. const OAUTH_SERVER = {
  2590. type: "http" as const,
  2591. url: "https://mcp.example.test/mcp",
  2592. oauth: { type: "authorization_code" as const },
  2593. };
  2594. const OAUTH_TOOLS = { tools: [{ name: "oauth_ping", inputSchema: { type: "object" } }] };
  2595. const AUTHORIZATION_URL = "https://auth.example.test/authorize";
  2596. const RECONNECT_WAIT_CAP_MS = 30_000;
  2597. const STATUS_POLL_ATTEMPTS = 50;
  2598. const STATUS_POLL_INTERVAL_MS = 10;
  2599. /** 发布授权链接后停在 gate 上;gate 以 error 结束时模拟授权到期或失败。 */
  2600. function publishAuthorizationThen(gate: Promise<"AUTHORIZED" | Error>) {
  2601. authMock.mockImplementation(async (provider: unknown) => {
  2602. const interactive = provider as {
  2603. redirectToAuthorization(url: URL): Promise<void>;
  2604. state(): Promise<string>;
  2605. };
  2606. const url = new URL(AUTHORIZATION_URL);
  2607. url.searchParams.set("state", await interactive.state());
  2608. await interactive.redirectToAuthorization(url);
  2609. const outcome = await gate;
  2610. if (outcome instanceof Error) throw outcome;
  2611. return outcome;
  2612. });
  2613. }
  2614. async function waitForSnapshot(
  2615. adapter: ReturnType<typeof createMcpAdapter>,
  2616. predicate: (row: ReturnType<typeof adapter.getToolSnapshot>[string] | undefined) => boolean,
  2617. ) {
  2618. for (let attempt = 0; attempt < STATUS_POLL_ATTEMPTS; attempt += 1) {
  2619. if (predicate(adapter.getToolSnapshot().runtime)) return;
  2620. await new Promise((resolve) => setTimeout(resolve, STATUS_POLL_INTERVAL_MS));
  2621. }
  2622. throw new Error(`snapshot did not converge: ${JSON.stringify(adapter.getToolSnapshot())}`);
  2623. }
  2624. /** 调用期 401 触发授权,授权以 error 结束;返回保留了目录的 adapter。 */
  2625. async function failToolCallAuthorization(failure: Error = new Error("authorization expired")) {
  2626. const gate = Promise.withResolvers<"AUTHORIZED" | Error>();
  2627. publishAuthorizationThen(gate.promise);
  2628. clientListToolsMock.mockResolvedValue(OAUTH_TOOLS as never);
  2629. clientCallToolMock.mockRejectedValueOnce(new UnauthorizedError());
  2630. const adapter = createMcpAdapter();
  2631. await adapter.connectServer("runtime", OAUTH_SERVER);
  2632. // 立即挂上处理:调用在链接发布时就会 reject,晚挂会被记为未处理 rejection。
  2633. const call = Promise.allSettled([
  2634. adapter.callTool({ serverName: "runtime", toolName: "oauth_ping" }),
  2635. ]);
  2636. await waitForSnapshot(adapter, (row) => Boolean(row?.status.authorization));
  2637. gate.resolve(failure);
  2638. await call;
  2639. await waitForSnapshot(
  2640. adapter,
  2641. (row) => row?.status.failureKind === "oauth_authorization_failed",
  2642. );
  2643. return adapter;
  2644. }
  2645. it("ends the triggering call once the authorization link is published", async () => {
  2646. const gate = Promise.withResolvers<"AUTHORIZED" | Error>();
  2647. publishAuthorizationThen(gate.promise);
  2648. clientListToolsMock.mockResolvedValue(OAUTH_TOOLS as never);
  2649. clientCallToolMock.mockRejectedValueOnce(new UnauthorizedError());
  2650. const adapter = createMcpAdapter();
  2651. await adapter.connectServer("runtime", OAUTH_SERVER);
  2652. const call = adapter.callTool(
  2653. { serverName: "runtime", toolName: "oauth_ping" },
  2654. { timeoutMs: RECONNECT_WAIT_CAP_MS },
  2655. );
  2656. try {
  2657. // 修复前要等满 30 s 才以工具超时结束,模型不知道需要用户授权。
  2658. const observed = await observePromiseWithin(call, 1_000);
  2659. expect(observed.status).toBe("rejected");
  2660. expect(String((observed as { reason: unknown }).reason)).toMatch(/Unauthorized/);
  2661. expect(adapter.getToolSnapshot().runtime?.status.authorization?.authorizationUrl).toContain(
  2662. AUTHORIZATION_URL,
  2663. );
  2664. // 授权仍在后台进行;完成后连接恢复,已结束的调用不被重放。
  2665. gate.resolve("AUTHORIZED");
  2666. await waitForSnapshot(adapter, (row) => row?.status.status === "connected");
  2667. expect(clientCallToolMock).toHaveBeenCalledTimes(1);
  2668. } finally {
  2669. gate.resolve("AUTHORIZED");
  2670. await Promise.allSettled([call]);
  2671. await adapter.close();
  2672. }
  2673. });
  2674. it("returns the original error when the reconnect wait reaches its cap", async () => {
  2675. clientListToolsMock.mockResolvedValue({
  2676. tools: [{ name: "ping", inputSchema: { type: "object" } }],
  2677. } as never);
  2678. const adapter = createMcpAdapter();
  2679. // 连接超时长于重连等待上限,等待一定先被上限截断。
  2680. await adapter.connectServer("demo", {
  2681. type: "http",
  2682. url: "https://mcp.example.test/mcp",
  2683. timeoutMs: RECONNECT_WAIT_CAP_MS * 10,
  2684. });
  2685. const reconnect = Promise.withResolvers<void>();
  2686. clientConnectMock.mockImplementation(() => reconnect.promise);
  2687. clientCallToolMock.mockRejectedValueOnce(
  2688. new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed"),
  2689. );
  2690. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  2691. try {
  2692. const observed = adapter
  2693. .callTool(
  2694. { serverName: "demo", toolName: "ping" },
  2695. { timeoutMs: RECONNECT_WAIT_CAP_MS * 4 },
  2696. )
  2697. .then(
  2698. () => undefined,
  2699. (error: unknown) => error,
  2700. );
  2701. await vi.advanceTimersByTimeAsync(RECONNECT_WAIT_CAP_MS);
  2702. const error = await observed;
  2703. // 修复前报 McpTimeoutError,模型以为工具超时,实际是连接关闭且仍在恢复。
  2704. expect(error).toBeInstanceOf(SdkError);
  2705. expect(String(error)).toContain("Connection closed");
  2706. } finally {
  2707. vi.useRealTimers();
  2708. reconnect.resolve();
  2709. await adapter.close();
  2710. }
  2711. });
  2712. it("keeps the tool directory when tool-call authorization ends without completing", async () => {
  2713. const adapter = await failToolCallAuthorization();
  2714. try {
  2715. // 修复前授权失败会清空目录,且之后没有任何重连入口,server 永久停在 needs-auth。
  2716. expect(adapter.getToolSnapshot().runtime?.tools?.map((item) => item.toolName)).toEqual([
  2717. "oauth_ping",
  2718. ]);
  2719. } finally {
  2720. await adapter.close();
  2721. }
  2722. });
  2723. it("keeps the tool directory when the authorization transaction times out", async () => {
  2724. // 授权事务到期由 withTimeout 抛出 McpTimeoutError。修复前 failConnection 先按超时归类为
  2725. // connection_timeout,覆盖调用方传入的 oauth_authorization_failed:目录被清空,也没有重连入口。
  2726. const adapter = await failToolCallAuthorization(
  2727. new McpTimeoutError("MCP server runtime OAuth authorization timed out"),
  2728. );
  2729. try {
  2730. expect(adapter.getToolSnapshot().runtime?.tools?.map((item) => item.toolName)).toEqual([
  2731. "oauth_ping",
  2732. ]);
  2733. } finally {
  2734. await adapter.close();
  2735. }
  2736. });
  2737. it("does not start an authorization when an MCP App reconnects", async () => {
  2738. const adapter = await failToolCallAuthorization();
  2739. try {
  2740. authMock.mockClear();
  2741. clientConnectMock.mockClear();
  2742. // 打开 MCP App 只传 reconnect:修复前会走授权失败重连,发起交互授权并发布链接。
  2743. await expect(
  2744. adapter.waitForServer("runtime", { reconnect: true, timeoutMs: 5_000 }),
  2745. ).resolves.toEqual({ timedOut: false });
  2746. expect(clientConnectMock).not.toHaveBeenCalled();
  2747. expect(authMock).not.toHaveBeenCalled();
  2748. const row = adapter.getToolSnapshot().runtime;
  2749. expect(row?.status.failureKind).toBe("oauth_authorization_failed");
  2750. expect(row?.status.authorization).toBeUndefined();
  2751. } finally {
  2752. await adapter.close();
  2753. }
  2754. });
  2755. it("reconnects once on the next execution with credentials authorized elsewhere", async () => {
  2756. const adapter = await failToolCallAuthorization();
  2757. try {
  2758. // 另一进程(设置页)已完成授权:Phase 1 直接连上,不再发起交互授权。
  2759. authMock.mockClear();
  2760. clientConnectMock.mockClear();
  2761. clientConnectMock.mockResolvedValue(undefined);
  2762. const waits = [
  2763. adapter.waitForServer("runtime", {
  2764. reconnect: true,
  2765. reauthorize: true,
  2766. timeoutMs: 5_000,
  2767. }),
  2768. adapter.waitForServer("runtime", {
  2769. reconnect: true,
  2770. reauthorize: true,
  2771. timeoutMs: 5_000,
  2772. }),
  2773. ];
  2774. // 重连期间保留目录,工具不会离开模型视图。
  2775. expect(adapter.getToolSnapshot().runtime?.tools?.map((item) => item.toolName)).toEqual([
  2776. "oauth_ping",
  2777. ]);
  2778. await expect(Promise.all(waits)).resolves.toEqual([
  2779. { timedOut: false },
  2780. { timedOut: false },
  2781. ]);
  2782. expect(adapter.getToolSnapshot().runtime?.status.status).toBe("connected");
  2783. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  2784. expect(authMock).not.toHaveBeenCalled();
  2785. await expect(
  2786. adapter.callTool({ serverName: "runtime", toolName: "oauth_ping" }),
  2787. ).resolves.toMatchObject({ content: [{ text: "ok" }] });
  2788. } finally {
  2789. await adapter.close();
  2790. }
  2791. });
  2792. it("starts a new authorization on the next execution when credentials are still missing", async () => {
  2793. const adapter = await failToolCallAuthorization();
  2794. const gate = Promise.withResolvers<"AUTHORIZED" | Error>();
  2795. try {
  2796. publishAuthorizationThen(gate.promise);
  2797. clientConnectMock.mockRejectedValueOnce(new UnauthorizedError());
  2798. // 授权链接发布即结束等待,调用方据此立即返回 needs-auth。
  2799. await expect(
  2800. observePromiseWithin(
  2801. adapter.waitForServer("runtime", {
  2802. reconnect: true,
  2803. reauthorize: true,
  2804. timeoutMs: 5_000,
  2805. }),
  2806. 1_000,
  2807. ),
  2808. ).resolves.toEqual({ status: "fulfilled", value: { timedOut: false } });
  2809. const row = adapter.getToolSnapshot().runtime;
  2810. expect(row?.status.authorization?.authorizationUrl).toContain(AUTHORIZATION_URL);
  2811. expect(row?.tools?.map((item) => item.toolName)).toEqual(["oauth_ping"]);
  2812. } finally {
  2813. gate.resolve(new Error("closed"));
  2814. await adapter.close();
  2815. }
  2816. });
  2817. });
  2818. it("converges Phase 2 orchestration errors to a retryable failed server status", async () => {
  2819. const credentialError = new Error("Unable to read shared ZCode credentials");
  2820. const credentialStore = {
  2821. filePath: "/tmp/zcode-unreadable-credentials.json",
  2822. load: vi.fn(async () => {
  2823. throw credentialError;
  2824. }),
  2825. loadMany: vi.fn(async () => {
  2826. throw credentialError;
  2827. }),
  2828. } as unknown as SharedZCodeCredentialStore;
  2829. clientConnectMock.mockRejectedValue(new UnauthorizedError());
  2830. const adapter = createMcpAdapter({
  2831. mcpOAuth: {
  2832. credentialStore,
  2833. },
  2834. });
  2835. const config = {
  2836. oauth: {
  2837. type: "authorization_code" as const,
  2838. },
  2839. type: "http" as const,
  2840. url: "https://mcp.example.test/mcp",
  2841. };
  2842. try {
  2843. await expect(adapter.connectConfiguredServers({ broken: config })).resolves.toMatchObject({
  2844. statuses: {
  2845. broken: {
  2846. error: "Unable to read shared ZCode credentials",
  2847. failureKind: "oauth_authorization_failed",
  2848. status: "failed",
  2849. },
  2850. },
  2851. });
  2852. await expect(adapter.status()).resolves.toMatchObject({
  2853. broken: {
  2854. failureKind: "oauth_authorization_failed",
  2855. status: "failed",
  2856. },
  2857. });
  2858. await expect(adapter.connectConfiguredServers({ broken: config })).resolves.toMatchObject({
  2859. statuses: {
  2860. broken: {
  2861. failureKind: "oauth_authorization_failed",
  2862. status: "failed",
  2863. },
  2864. },
  2865. });
  2866. // 相同配置 reconcile 不重试失败连接;显式连接操作(revalidate)仍可重试。
  2867. expect(clientConnectMock).toHaveBeenCalledTimes(1);
  2868. await adapter.connectServer("broken", config, { revalidate: true });
  2869. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  2870. } finally {
  2871. await adapter.close();
  2872. }
  2873. });
  2874. it("only opens OAuth authorization URL when an opener is injected", async () => {
  2875. const openAuthorizationUrl = vi.fn(async () => {});
  2876. const { release: resolveConnect } = stubInteractiveAuthorization(
  2877. "https://auth.example.test/authorize?state=state_test",
  2878. );
  2879. const adapter = createMcpAdapter({
  2880. mcpOAuth: {
  2881. openAuthorizationUrl,
  2882. },
  2883. });
  2884. const connect = adapter.connectServer("notion", {
  2885. type: "http",
  2886. url: "https://mcp.example.test/mcp",
  2887. oauth: {
  2888. type: "authorization_code",
  2889. clientName: "ZCode",
  2890. },
  2891. });
  2892. for (let attempt = 0; attempt < 20; attempt += 1) {
  2893. const status = await adapter.status();
  2894. if (status.notion?.authorization?.authorizationUrl) break;
  2895. await new Promise((resolve) => setTimeout(resolve, 10));
  2896. }
  2897. expect(openAuthorizationUrl).toHaveBeenCalledWith(
  2898. expect.objectContaining({
  2899. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  2900. serverName: "notion",
  2901. }),
  2902. );
  2903. resolveConnect();
  2904. await expect(connect).resolves.toMatchObject({
  2905. status: "connected",
  2906. toolCount: 0,
  2907. });
  2908. await adapter.close();
  2909. });
  2910. describe("async startup snapshot and wait", () => {
  2911. const LIST_CHANGED = "notifications/tools/list_changed";
  2912. const stdio = { type: "stdio" as const, command: "node" };
  2913. const tool = (name: string) => ({ name, inputSchema: { type: "object", properties: {} } });
  2914. it("reads memory only: no tools while connecting, an empty list is distinct after connect", async () => {
  2915. const gate = Promise.withResolvers<void>();
  2916. clientConnectMock.mockImplementationOnce(() => gate.promise);
  2917. const adapter = createMcpAdapter();
  2918. const connecting = adapter.connectServer("demo", stdio);
  2919. await vi.waitFor(() => expect(clientConnectMock).toHaveBeenCalledOnce());
  2920. const before = adapter.getToolSnapshot!();
  2921. expect(before.demo?.status.status).toBe("connecting");
  2922. expect(before.demo?.tools).toBeUndefined();
  2923. expect(before.demo?.toolsVersion).toBeUndefined();
  2924. gate.resolve();
  2925. await connecting;
  2926. const after = adapter.getToolSnapshot!();
  2927. expect(after.demo?.status.status).toBe("connected");
  2928. expect(after.demo?.tools).toEqual([]);
  2929. expect(after.demo?.toolsVersion).toEqual(expect.any(String));
  2930. await adapter.close();
  2931. });
  2932. it("refreshes list_changed in the background and keeps alwaysLoad", async () => {
  2933. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("a")] });
  2934. const adapter = createMcpAdapter();
  2935. await adapter.connectServer("demo", { ...stdio, alwaysLoad: true });
  2936. const first = adapter.getToolSnapshot!().demo!;
  2937. const refresh = Promise.withResolvers<{ tools: unknown[] }>();
  2938. clientListToolsMock.mockImplementationOnce(() => refresh.promise);
  2939. capturedClients.at(-1)!.notificationHandlers.get(LIST_CHANGED)!({});
  2940. await vi.waitFor(() => expect(clientListToolsMock).toHaveBeenCalledTimes(2));
  2941. // 刷新进行中:快照立即返回旧列表,不等待网络。
  2942. const during = adapter.getToolSnapshot!().demo!;
  2943. expect(during.toolsVersion).toBe(first.toolsVersion);
  2944. expect(during.tools?.map((item) => item.toolName)).toEqual(["a"]);
  2945. refresh.resolve({ tools: [tool("b")] });
  2946. await vi.waitFor(() =>
  2947. expect(adapter.getToolSnapshot!().demo!.tools?.map((item) => item.toolName)).toEqual(["b"]),
  2948. );
  2949. const after = adapter.getToolSnapshot!().demo!;
  2950. expect(after.toolsVersion).not.toBe(first.toolsVersion);
  2951. expect(after.tools?.[0]?.alwaysLoad).toBe(true);
  2952. expect(after.status.toolCount).toBe(1);
  2953. await adapter.close();
  2954. });
  2955. it("retries a failed list refresh in the producer while snapshot reads stay pure", async () => {
  2956. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("a")] });
  2957. const adapter = createMcpAdapter();
  2958. await adapter.connectServer("demo", stdio);
  2959. const first = adapter.getToolSnapshot!().demo!;
  2960. const handler = capturedClients.at(-1)!.notificationHandlers.get(LIST_CHANGED)!;
  2961. const failed = Promise.withResolvers<{ tools: unknown[] }>();
  2962. clientListToolsMock.mockImplementationOnce(() => failed.promise);
  2963. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("c")] });
  2964. handler({});
  2965. failed.reject(new Error("list failed"));
  2966. await vi.waitFor(() => expect(clientListToolsMock).toHaveBeenCalledTimes(2));
  2967. // 清空一轮宏任务,确保失败分支已执行完(脏标记已重新置位),而不是靠 sleep。
  2968. await new Promise((resolve) => setImmediate(resolve));
  2969. expect(adapter.getToolSnapshot!().demo!.toolsVersion).toBe(first.toolsVersion);
  2970. // 失败后保留脏标记,但读快照只读内存,反复读取也不会发起 tools/list。
  2971. for (let index = 0; index < 3; index += 1) adapter.getToolSnapshot!();
  2972. expect(clientListToolsMock).toHaveBeenCalledTimes(2);
  2973. // 无第二次通知,也无 listTools 调用;由连接层推进失败后的重试。
  2974. await vi.waitFor(
  2975. () =>
  2976. expect(adapter.getToolSnapshot!().demo!.tools?.map((item) => item.toolName)).toEqual([
  2977. "c",
  2978. ]),
  2979. { timeout: 2000 },
  2980. );
  2981. expect(clientListToolsMock).toHaveBeenCalledTimes(3);
  2982. await adapter.close();
  2983. });
  2984. it("cancels a list refresh backoff when its connection closes", async () => {
  2985. vi.useFakeTimers();
  2986. const adapter = createMcpAdapter();
  2987. try {
  2988. await adapter.connectServer("demo", stdio);
  2989. clientListToolsMock.mockRejectedValueOnce(new Error("temporary list failure"));
  2990. capturedClients.at(-1)!.notificationHandlers.get(LIST_CHANGED)!({});
  2991. await vi.advanceTimersByTimeAsync(0);
  2992. expect(vi.getTimerCount()).toBeGreaterThan(0);
  2993. await adapter.disconnectServer("demo");
  2994. await vi.advanceTimersByTimeAsync(0);
  2995. expect(vi.getTimerCount()).toBe(0);
  2996. expect(clientListToolsMock).toHaveBeenCalledTimes(2);
  2997. } finally {
  2998. await adapter.close();
  2999. vi.useRealTimers();
  3000. }
  3001. });
  3002. it("ignores a late list_changed from a replaced client", async () => {
  3003. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("old")] });
  3004. const adapter = createMcpAdapter();
  3005. await adapter.connectServer("demo", stdio);
  3006. const oldHandler = capturedClients.at(-1)!.notificationHandlers.get(LIST_CHANGED)!;
  3007. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("fresh")] });
  3008. await adapter.connectServer("demo", { ...stdio, args: ["replacement"] });
  3009. const replaced = adapter.getToolSnapshot!().demo!;
  3010. const calls = clientListToolsMock.mock.calls.length;
  3011. oldHandler({});
  3012. await Promise.resolve();
  3013. expect(clientListToolsMock).toHaveBeenCalledTimes(calls);
  3014. expect(adapter.getToolSnapshot!().demo!).toEqual(replaced);
  3015. await adapter.close();
  3016. });
  3017. it("runs one more pass when list_changed arrives during a refresh", async () => {
  3018. const adapter = createMcpAdapter();
  3019. await adapter.connectServer("demo", stdio);
  3020. const handler = capturedClients.at(-1)!.notificationHandlers.get(LIST_CHANGED)!;
  3021. const firstRefresh = Promise.withResolvers<{ tools: unknown[] }>();
  3022. clientListToolsMock.mockImplementationOnce(() => firstRefresh.promise);
  3023. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("second")] });
  3024. handler({});
  3025. await vi.waitFor(() => expect(clientListToolsMock).toHaveBeenCalledTimes(2));
  3026. handler({});
  3027. // single-flight:进行中的刷新不会并发第二次 tools/list。
  3028. expect(clientListToolsMock).toHaveBeenCalledTimes(2);
  3029. firstRefresh.resolve({ tools: [tool("first")] });
  3030. await vi.waitFor(() =>
  3031. expect(adapter.getToolSnapshot!().demo!.tools?.map((item) => item.toolName)).toEqual([
  3032. "second",
  3033. ]),
  3034. );
  3035. expect(clientListToolsMock).toHaveBeenCalledTimes(3);
  3036. await adapter.close();
  3037. });
  3038. it("drops a late refresh result after the connection is replaced", async () => {
  3039. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("old")] });
  3040. const adapter = createMcpAdapter();
  3041. await adapter.connectServer("demo", stdio);
  3042. const late = Promise.withResolvers<{ tools: unknown[] }>();
  3043. clientListToolsMock.mockImplementationOnce(() => late.promise);
  3044. capturedClients.at(-1)!.notificationHandlers.get(LIST_CHANGED)!({});
  3045. await vi.waitFor(() => expect(clientListToolsMock).toHaveBeenCalledTimes(2));
  3046. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("fresh")] });
  3047. await adapter.connectServer("demo", { ...stdio, args: ["replacement"] });
  3048. const replaced = adapter.getToolSnapshot!().demo!;
  3049. late.resolve({ tools: [tool("late")] });
  3050. await Promise.resolve();
  3051. await Promise.resolve();
  3052. expect(adapter.getToolSnapshot!().demo!).toEqual(replaced);
  3053. expect(replaced.tools?.map((item) => item.toolName)).toEqual(["fresh"]);
  3054. await adapter.close();
  3055. });
  3056. it("removes the stdio directory after an unexpected disconnect", async () => {
  3057. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("a")] });
  3058. const adapter = createMcpAdapter();
  3059. await adapter.connectServer("demo", stdio);
  3060. const first = adapter.getToolSnapshot!().demo!;
  3061. capturedClients.at(-1)!.onclose?.();
  3062. const after = adapter.getToolSnapshot!().demo!;
  3063. expect(first.tools).toHaveLength(1);
  3064. expect(after.status.status).toBe("failed");
  3065. expect(after.toolsVersion).toBeUndefined();
  3066. expect(after.tools).toBeUndefined();
  3067. await adapter.close();
  3068. });
  3069. it("waits for the shared startup with a bound and cancel without closing the connection", async () => {
  3070. const gate = Promise.withResolvers<void>();
  3071. clientConnectMock.mockImplementationOnce(() => gate.promise);
  3072. const adapter = createMcpAdapter();
  3073. const connecting = adapter.connectServer("demo", stdio);
  3074. await vi.waitFor(() => expect(clientConnectMock).toHaveBeenCalledOnce());
  3075. await expect(adapter.waitForServer!("demo", { timeoutMs: 1 })).resolves.toEqual({
  3076. timedOut: true,
  3077. });
  3078. const abort = new AbortController();
  3079. const aborted = adapter.waitForServer!("demo", { signal: abort.signal, timeoutMs: 60_000 });
  3080. abort.abort(new Error("caller cancelled"));
  3081. await expect(aborted).rejects.toThrow("caller cancelled");
  3082. expect(adapter.getToolSnapshot!().demo!.status.status).toBe("connecting");
  3083. const waiting = adapter.waitForServer!("demo", { timeoutMs: 60_000 });
  3084. gate.resolve();
  3085. await expect(waiting).resolves.toEqual({ timedOut: false });
  3086. await connecting;
  3087. expect(clientConnectMock).toHaveBeenCalledOnce();
  3088. await expect(adapter.waitForServer!("demo", { timeoutMs: 1 })).resolves.toEqual({
  3089. timedOut: false,
  3090. });
  3091. await expect(adapter.waitForServer!("missing", { timeoutMs: 1 })).resolves.toEqual({
  3092. timedOut: false,
  3093. });
  3094. await adapter.close();
  3095. });
  3096. it("reconnects a disconnected server only when the execution check asks for it", async () => {
  3097. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("a")] });
  3098. const adapter = createMcpAdapter();
  3099. await adapter.connectServer("demo", stdio);
  3100. capturedClients.at(-1)!.onclose?.();
  3101. // WaitForMcpServers 不带 reconnect:断线 server 不自动重连。
  3102. await expect(adapter.waitForServer!("demo", { timeoutMs: 60_000 })).resolves.toEqual({
  3103. timedOut: false,
  3104. });
  3105. expect(clientConnectMock).toHaveBeenCalledOnce();
  3106. expect(adapter.getToolSnapshot!().demo!.status.status).toBe("failed");
  3107. clientListToolsMock.mockResolvedValueOnce({ tools: [tool("b")] });
  3108. await expect(
  3109. adapter.waitForServer!("demo", { timeoutMs: 60_000, reconnect: true }),
  3110. ).resolves.toEqual({ timedOut: false });
  3111. expect(clientConnectMock).toHaveBeenCalledTimes(2);
  3112. const recovered = adapter.getToolSnapshot!().demo!;
  3113. expect(recovered.status.status).toBe("connected");
  3114. expect(recovered.tools?.map((item) => item.toolName)).toEqual(["b"]);
  3115. await adapter.close();
  3116. });
  3117. it("keeps a waiter pending while a reconnect is still closing the previous connection", async () => {
  3118. const adapter = createMcpAdapter();
  3119. await adapter.connectServer("demo", stdio);
  3120. const closing = Promise.withResolvers<void>();
  3121. clientCloseMock.mockImplementationOnce(() => closing.promise);
  3122. const reconnecting = adapter.connectServer("demo", { ...stdio, args: ["replacement"] });
  3123. // 旧连接还在关闭、新握手尚未开始:新的 connecting 记录必须已登记,等待不能凭旧的 connected 记录立即成功。
  3124. expect(adapter.getToolSnapshot!().demo!.status.status).toBe("connecting");
  3125. await expect(adapter.waitForServer!("demo", { timeoutMs: 1 })).resolves.toEqual({
  3126. timedOut: true,
  3127. });
  3128. const waiting = adapter.waitForServer!("demo", { timeoutMs: 60_000 });
  3129. closing.resolve();
  3130. await expect(waiting).resolves.toEqual({ timedOut: false });
  3131. await expect(reconnecting).resolves.toMatchObject({ status: "connected" });
  3132. await adapter.close();
  3133. });
  3134. it("returns a waiter as soon as startup turns into a pending OAuth authorization", async () => {
  3135. const beforeAuthorization = Promise.withResolvers<void>();
  3136. const { release } = stubInteractiveAuthorization(
  3137. "https://auth.example.test/authorize?state=state_wait",
  3138. beforeAuthorization.promise,
  3139. );
  3140. const adapter = createMcpAdapter();
  3141. const connecting = adapter.connectServer("notion", {
  3142. type: "http",
  3143. url: "https://mcp.example.test/mcp",
  3144. oauth: { type: "authorization_code", clientName: "ZCode" },
  3145. });
  3146. await vi.waitFor(() => expect(authMock).toHaveBeenCalled());
  3147. expect(adapter.getToolSnapshot!().notion?.status.authorization).toBeUndefined();
  3148. // 调用开始时只是普通 connecting;授权需要用户处理时立即结束本次等待,不等满预算。
  3149. const waiting = adapter.waitForServer!("notion", { timeoutMs: 60_000 });
  3150. beforeAuthorization.resolve();
  3151. await expect(waiting).resolves.toEqual({ timedOut: false });
  3152. expect(adapter.getToolSnapshot!().notion?.status.authorization?.authorizationUrl).toBe(
  3153. "https://auth.example.test/authorize?state=state_wait",
  3154. );
  3155. // 已处于授权等待时再调用,也立即返回;底层授权不被取消。
  3156. await expect(adapter.waitForServer!("notion", { timeoutMs: 60_000 })).resolves.toEqual({
  3157. timedOut: false,
  3158. });
  3159. release();
  3160. await expect(connecting).resolves.toMatchObject({ status: "connected" });
  3161. await adapter.close();
  3162. });
  3163. });
  3164. it("retries list refresh on the recovered connection and cancels it when that connection closes", async () => {
  3165. const adapter = createMcpAdapter();
  3166. const tool = (name: string) => ({ name, inputSchema: { type: "object" } });
  3167. clientListToolsMock.mockResolvedValue({ tools: [tool("old")] } as never);
  3168. await adapter.connectServer("remote", { type: "sse", url: "https://example.test/mcp" });
  3169. capturedClients.at(-1)!.onclose?.();
  3170. await adapter.waitForServer!("remote", { timeoutMs: 1000 });
  3171. expect(adapter.getToolSnapshot!().remote?.status.status).toBe("connected");
  3172. vi.useFakeTimers();
  3173. try {
  3174. clientListToolsMock
  3175. .mockRejectedValueOnce(new Error("transient list failure"))
  3176. .mockResolvedValueOnce({ tools: [tool("new")] } as never);
  3177. capturedClients.at(-1)!.notificationHandlers.get("notifications/tools/list_changed")!({});
  3178. await vi.advanceTimersByTimeAsync(1000);
  3179. expect(adapter.getToolSnapshot!().remote?.tools?.map((t) => t.toolName)).toEqual(["new"]);
  3180. clientListToolsMock.mockRejectedValue(new Error("another list failure"));
  3181. capturedClients.at(-1)!.notificationHandlers.get("notifications/tools/list_changed")!({});
  3182. await vi.advanceTimersByTimeAsync(0);
  3183. const calls = clientListToolsMock.mock.calls.length;
  3184. await adapter.close();
  3185. await vi.runAllTimersAsync();
  3186. expect(clientListToolsMock).toHaveBeenCalledTimes(calls);
  3187. } finally {
  3188. vi.useRealTimers();
  3189. await adapter.close();
  3190. }
  3191. });
  3192. });
  3193. // 回归:远程意外断连在后台恢复,等待期间不丢目录。
  3194. it("keeps remote tools pending until shared background recovery settles", async () => {
  3195. const adapter = createMcpAdapter();
  3196. clientListToolsMock.mockResolvedValue({
  3197. tools: [{ name: "ping", inputSchema: { type: "object" } }],
  3198. } as never);
  3199. await adapter.connectServer("remote", { type: "http", url: "https://example.test/mcp" });
  3200. const release = Promise.withResolvers<void>();
  3201. clientConnectMock.mockImplementationOnce(() => release.promise);
  3202. capturedClients.at(-1)!.onclose?.();
  3203. expect(adapter.getToolSnapshot?.()?.remote?.status.status).toBe("connecting");
  3204. expect(adapter.getToolSnapshot?.()?.remote?.tools?.[0]?.toolName).toBe("ping");
  3205. const waiting = adapter.waitForServer!("remote", { timeoutMs: 1000 });
  3206. release.resolve();
  3207. await waiting;
  3208. expect(adapter.getToolSnapshot?.()?.remote?.status.status).toBe("connected");
  3209. await adapter.close();
  3210. });
  3211. it("exhausts five remote recovery attempts and drops the retained directory", async () => {
  3212. const adapter = createMcpAdapter();
  3213. clientListToolsMock.mockResolvedValue({
  3214. tools: [{ name: "ping", inputSchema: { type: "object" } }],
  3215. } as never);
  3216. await adapter.connectServer("remote", { type: "http", url: "https://example.test/mcp" });
  3217. const calls = clientConnectMock.mock.calls.length;
  3218. vi.useFakeTimers();
  3219. try {
  3220. clientConnectMock.mockRejectedValue(new Error("offline"));
  3221. capturedClients.at(-1)!.onclose?.();
  3222. expect(adapter.getToolSnapshot!().remote?.status.status).toBe("connecting");
  3223. await vi.runAllTimersAsync();
  3224. expect(clientConnectMock.mock.calls.length - calls).toBe(5);
  3225. expect(adapter.getToolSnapshot!().remote?.status.status).toBe("failed");
  3226. expect(await adapter.listTools()).toEqual([]);
  3227. } finally {
  3228. vi.useRealTimers();
  3229. await adapter.close();
  3230. }
  3231. });