lifecycle.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. import { test, expect, mock, beforeEach } from "bun:test"
  2. import { Effect } from "effect"
  3. import type { MCP as MCPNS } from "../../src/mcp/index"
  4. // --- Mock infrastructure ---
  5. // Per-client state for controlling mock behavior
  6. interface MockClientState {
  7. tools: Array<{ name: string; description?: string; inputSchema: object }>
  8. listToolsCalls: number
  9. listToolsShouldFail: boolean
  10. listToolsError: string
  11. listPromptsShouldFail: boolean
  12. listResourcesShouldFail: boolean
  13. prompts: Array<{ name: string; description?: string }>
  14. resources: Array<{ name: string; uri: string; description?: string }>
  15. closed: boolean
  16. notificationHandlers: Map<unknown, (...args: any[]) => any>
  17. }
  18. const clientStates = new Map<string, MockClientState>()
  19. let lastCreatedClientName: string | undefined
  20. let connectShouldFail = false
  21. let connectShouldHang = false
  22. let connectError = "Mock transport cannot connect"
  23. // Tracks how many Client instances were created (detects leaks)
  24. let clientCreateCount = 0
  25. // Tracks how many times transport.close() is called across all mock transports
  26. let transportCloseCount = 0
  27. function getOrCreateClientState(name?: string): MockClientState {
  28. const key = name ?? "default"
  29. let state = clientStates.get(key)
  30. if (!state) {
  31. state = {
  32. tools: [{ name: "test_tool", description: "A test tool", inputSchema: { type: "object", properties: {} } }],
  33. listToolsCalls: 0,
  34. listToolsShouldFail: false,
  35. listToolsError: "listTools failed",
  36. listPromptsShouldFail: false,
  37. listResourcesShouldFail: false,
  38. prompts: [],
  39. resources: [],
  40. closed: false,
  41. notificationHandlers: new Map(),
  42. }
  43. clientStates.set(key, state)
  44. }
  45. return state
  46. }
  47. // Mock transport that succeeds or fails based on connectShouldFail / connectShouldHang
  48. class MockStdioTransport {
  49. stderr: null = null
  50. pid = 12345
  51. constructor(_opts: any) {}
  52. async start() {
  53. if (connectShouldHang) return new Promise<void>(() => {}) // never resolves
  54. if (connectShouldFail) throw new Error(connectError)
  55. }
  56. async close() {
  57. transportCloseCount++
  58. }
  59. }
  60. class MockStreamableHTTP {
  61. constructor(_url: URL, _opts?: any) {}
  62. async start() {
  63. if (connectShouldHang) return new Promise<void>(() => {}) // never resolves
  64. if (connectShouldFail) throw new Error(connectError)
  65. }
  66. async close() {
  67. transportCloseCount++
  68. }
  69. async finishAuth() {}
  70. }
  71. class MockSSE {
  72. constructor(_url: URL, _opts?: any) {}
  73. async start() {
  74. if (connectShouldHang) return new Promise<void>(() => {}) // never resolves
  75. if (connectShouldFail) throw new Error(connectError)
  76. }
  77. async close() {
  78. transportCloseCount++
  79. }
  80. }
  81. mock.module("@modelcontextprotocol/sdk/client/stdio.js", () => ({
  82. StdioClientTransport: MockStdioTransport,
  83. }))
  84. mock.module("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({
  85. StreamableHTTPClientTransport: MockStreamableHTTP,
  86. }))
  87. mock.module("@modelcontextprotocol/sdk/client/sse.js", () => ({
  88. SSEClientTransport: MockSSE,
  89. }))
  90. mock.module("@modelcontextprotocol/sdk/client/auth.js", () => ({
  91. UnauthorizedError: class extends Error {
  92. constructor() {
  93. super("Unauthorized")
  94. }
  95. },
  96. }))
  97. // Mock Client that delegates to per-name MockClientState
  98. mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({
  99. Client: class MockClient {
  100. _state!: MockClientState
  101. transport: any
  102. constructor(_opts: any) {
  103. clientCreateCount++
  104. }
  105. async connect(transport: { start: () => Promise<void> }) {
  106. this.transport = transport
  107. await transport.start()
  108. // After successful connect, bind to the last-created client name
  109. this._state = getOrCreateClientState(lastCreatedClientName)
  110. }
  111. setNotificationHandler(schema: unknown, handler: (...args: any[]) => any) {
  112. this._state?.notificationHandlers.set(schema, handler)
  113. }
  114. async listTools() {
  115. if (this._state) this._state.listToolsCalls++
  116. if (this._state?.listToolsShouldFail) {
  117. throw new Error(this._state.listToolsError)
  118. }
  119. return { tools: this._state?.tools ?? [] }
  120. }
  121. async listPrompts() {
  122. if (this._state?.listPromptsShouldFail) {
  123. throw new Error("listPrompts failed")
  124. }
  125. return { prompts: this._state?.prompts ?? [] }
  126. }
  127. async listResources() {
  128. if (this._state?.listResourcesShouldFail) {
  129. throw new Error("listResources failed")
  130. }
  131. return { resources: this._state?.resources ?? [] }
  132. }
  133. async close() {
  134. if (this._state) this._state.closed = true
  135. }
  136. },
  137. }))
  138. beforeEach(() => {
  139. clientStates.clear()
  140. lastCreatedClientName = undefined
  141. connectShouldFail = false
  142. connectShouldHang = false
  143. connectError = "Mock transport cannot connect"
  144. clientCreateCount = 0
  145. transportCloseCount = 0
  146. })
  147. // Import after mocks
  148. const { MCP } = await import("../../src/mcp/index")
  149. const { Instance } = await import("../../src/project/instance")
  150. const { tmpdir } = await import("../fixture/fixture")
  151. // --- Helper ---
  152. function withInstance(
  153. config: Record<string, unknown>,
  154. fn: (mcp: MCPNS.Interface) => Effect.Effect<void, unknown, never>,
  155. ) {
  156. return async () => {
  157. await using tmp = await tmpdir({
  158. init: async (dir) => {
  159. await Bun.write(
  160. `${dir}/opencode.json`,
  161. JSON.stringify({
  162. $schema: "https://opencode.ai/config.json",
  163. mcp: config,
  164. }),
  165. )
  166. },
  167. })
  168. await Instance.provide({
  169. directory: tmp.path,
  170. fn: async () => {
  171. await Effect.runPromise(MCP.Service.use(fn).pipe(Effect.provide(MCP.defaultLayer)))
  172. // dispose instance to clean up state between tests
  173. await Instance.dispose()
  174. },
  175. })
  176. }
  177. }
  178. // ========================================================================
  179. // Test: tools() are cached after connect
  180. // ========================================================================
  181. test(
  182. "tools() reuses cached tool definitions after connect",
  183. withInstance({}, (mcp) =>
  184. Effect.gen(function* () {
  185. lastCreatedClientName = "my-server"
  186. const serverState = getOrCreateClientState("my-server")
  187. serverState.tools = [
  188. { name: "do_thing", description: "does a thing", inputSchema: { type: "object", properties: {} } },
  189. ]
  190. // First: add the server successfully
  191. const addResult = yield* mcp.add("my-server", {
  192. type: "local",
  193. command: ["echo", "test"],
  194. })
  195. expect((addResult.status as any)["my-server"]?.status ?? (addResult.status as any).status).toBe("connected")
  196. expect(serverState.listToolsCalls).toBe(1)
  197. const toolsA = yield* mcp.tools()
  198. const toolsB = yield* mcp.tools()
  199. expect(Object.keys(toolsA).length).toBeGreaterThan(0)
  200. expect(Object.keys(toolsB).length).toBeGreaterThan(0)
  201. expect(serverState.listToolsCalls).toBe(1)
  202. }),
  203. ),
  204. )
  205. // ========================================================================
  206. // Test: tool change notifications refresh the cache
  207. // ========================================================================
  208. test(
  209. "tool change notifications refresh cached tool definitions",
  210. withInstance({}, (mcp) =>
  211. Effect.gen(function* () {
  212. lastCreatedClientName = "status-server"
  213. const serverState = getOrCreateClientState("status-server")
  214. yield* mcp.add("status-server", {
  215. type: "local",
  216. command: ["echo", "test"],
  217. })
  218. const before = yield* mcp.tools()
  219. expect(Object.keys(before).some((key) => key.includes("test_tool"))).toBe(true)
  220. expect(serverState.listToolsCalls).toBe(1)
  221. serverState.tools = [{ name: "next_tool", description: "next", inputSchema: { type: "object", properties: {} } }]
  222. const handler = Array.from(serverState.notificationHandlers.values())[0]
  223. expect(handler).toBeDefined()
  224. yield* Effect.promise(() => handler?.())
  225. const after = yield* mcp.tools()
  226. expect(Object.keys(after).some((key) => key.includes("next_tool"))).toBe(true)
  227. expect(Object.keys(after).some((key) => key.includes("test_tool"))).toBe(false)
  228. expect(serverState.listToolsCalls).toBe(2)
  229. }),
  230. ),
  231. )
  232. // ========================================================================
  233. // Test: connect() / disconnect() lifecycle
  234. // ========================================================================
  235. test(
  236. "disconnect sets status to disabled and removes client",
  237. withInstance(
  238. {
  239. "disc-server": {
  240. type: "local",
  241. command: ["echo", "test"],
  242. },
  243. },
  244. (mcp) =>
  245. Effect.gen(function* () {
  246. lastCreatedClientName = "disc-server"
  247. getOrCreateClientState("disc-server")
  248. yield* mcp.add("disc-server", {
  249. type: "local",
  250. command: ["echo", "test"],
  251. })
  252. const statusBefore = yield* mcp.status()
  253. expect(statusBefore["disc-server"]?.status).toBe("connected")
  254. yield* mcp.disconnect("disc-server")
  255. const statusAfter = yield* mcp.status()
  256. expect(statusAfter["disc-server"]?.status).toBe("disabled")
  257. // Tools should be empty after disconnect
  258. const tools = yield* mcp.tools()
  259. const serverTools = Object.keys(tools).filter((k) => k.startsWith("disc-server"))
  260. expect(serverTools.length).toBe(0)
  261. }),
  262. ),
  263. )
  264. test(
  265. "connect() after disconnect() re-establishes the server",
  266. withInstance(
  267. {
  268. "reconn-server": {
  269. type: "local",
  270. command: ["echo", "test"],
  271. },
  272. },
  273. (mcp) =>
  274. Effect.gen(function* () {
  275. lastCreatedClientName = "reconn-server"
  276. const serverState = getOrCreateClientState("reconn-server")
  277. serverState.tools = [
  278. { name: "my_tool", description: "a tool", inputSchema: { type: "object", properties: {} } },
  279. ]
  280. yield* mcp.add("reconn-server", {
  281. type: "local",
  282. command: ["echo", "test"],
  283. })
  284. yield* mcp.disconnect("reconn-server")
  285. expect((yield* mcp.status())["reconn-server"]?.status).toBe("disabled")
  286. // Reconnect
  287. yield* mcp.connect("reconn-server")
  288. expect((yield* mcp.status())["reconn-server"]?.status).toBe("connected")
  289. const tools = yield* mcp.tools()
  290. expect(Object.keys(tools).some((k) => k.includes("my_tool"))).toBe(true)
  291. }),
  292. ),
  293. )
  294. // ========================================================================
  295. // Test: add() closes existing client before replacing
  296. // ========================================================================
  297. test(
  298. "add() closes the old client when replacing a server",
  299. // Don't put the server in config — add it dynamically so we control
  300. // exactly which client instance is "first" vs "second".
  301. withInstance({}, (mcp) =>
  302. Effect.gen(function* () {
  303. lastCreatedClientName = "replace-server"
  304. const firstState = getOrCreateClientState("replace-server")
  305. yield* mcp.add("replace-server", {
  306. type: "local",
  307. command: ["echo", "test"],
  308. })
  309. expect(firstState.closed).toBe(false)
  310. // Create new state for second client
  311. clientStates.delete("replace-server")
  312. const secondState = getOrCreateClientState("replace-server")
  313. // Re-add should close the first client
  314. yield* mcp.add("replace-server", {
  315. type: "local",
  316. command: ["echo", "test"],
  317. })
  318. expect(firstState.closed).toBe(true)
  319. expect(secondState.closed).toBe(false)
  320. }),
  321. ),
  322. )
  323. // ========================================================================
  324. // Test: state init with mixed success/failure
  325. // ========================================================================
  326. test(
  327. "init connects available servers even when one fails",
  328. withInstance(
  329. {
  330. "good-server": {
  331. type: "local",
  332. command: ["echo", "good"],
  333. },
  334. "bad-server": {
  335. type: "local",
  336. command: ["echo", "bad"],
  337. },
  338. },
  339. (mcp) =>
  340. Effect.gen(function* () {
  341. // Set up good server
  342. const goodState = getOrCreateClientState("good-server")
  343. goodState.tools = [{ name: "good_tool", description: "works", inputSchema: { type: "object", properties: {} } }]
  344. // Set up bad server - will fail on listTools during create()
  345. const badState = getOrCreateClientState("bad-server")
  346. badState.listToolsShouldFail = true
  347. // Add good server first
  348. lastCreatedClientName = "good-server"
  349. yield* mcp.add("good-server", {
  350. type: "local",
  351. command: ["echo", "good"],
  352. })
  353. // Add bad server - should fail but not affect good server
  354. lastCreatedClientName = "bad-server"
  355. yield* mcp.add("bad-server", {
  356. type: "local",
  357. command: ["echo", "bad"],
  358. })
  359. const status = yield* mcp.status()
  360. expect(status["good-server"]?.status).toBe("connected")
  361. expect(status["bad-server"]?.status).toBe("failed")
  362. // Good server's tools should still be available
  363. const tools = yield* mcp.tools()
  364. expect(Object.keys(tools).some((k) => k.includes("good_tool"))).toBe(true)
  365. }),
  366. ),
  367. )
  368. // ========================================================================
  369. // Test: disabled server via config
  370. // ========================================================================
  371. test(
  372. "disabled server is marked as disabled without attempting connection",
  373. withInstance(
  374. {
  375. "disabled-server": {
  376. type: "local",
  377. command: ["echo", "test"],
  378. enabled: false,
  379. },
  380. },
  381. (mcp) =>
  382. Effect.gen(function* () {
  383. const countBefore = clientCreateCount
  384. yield* mcp.add("disabled-server", {
  385. type: "local",
  386. command: ["echo", "test"],
  387. enabled: false,
  388. } as any)
  389. // No client should have been created
  390. expect(clientCreateCount).toBe(countBefore)
  391. const status = yield* mcp.status()
  392. expect(status["disabled-server"]?.status).toBe("disabled")
  393. }),
  394. ),
  395. )
  396. // ========================================================================
  397. // Test: prompts() and resources()
  398. // ========================================================================
  399. test(
  400. "prompts() returns prompts from connected servers",
  401. withInstance(
  402. {
  403. "prompt-server": {
  404. type: "local",
  405. command: ["echo", "test"],
  406. },
  407. },
  408. (mcp) =>
  409. Effect.gen(function* () {
  410. lastCreatedClientName = "prompt-server"
  411. const serverState = getOrCreateClientState("prompt-server")
  412. serverState.prompts = [{ name: "my-prompt", description: "A test prompt" }]
  413. yield* mcp.add("prompt-server", {
  414. type: "local",
  415. command: ["echo", "test"],
  416. })
  417. const prompts = yield* mcp.prompts()
  418. expect(Object.keys(prompts).length).toBe(1)
  419. const key = Object.keys(prompts)[0]
  420. expect(key).toContain("prompt-server")
  421. expect(key).toContain("my-prompt")
  422. }),
  423. ),
  424. )
  425. test(
  426. "resources() returns resources from connected servers",
  427. withInstance(
  428. {
  429. "resource-server": {
  430. type: "local",
  431. command: ["echo", "test"],
  432. },
  433. },
  434. (mcp) =>
  435. Effect.gen(function* () {
  436. lastCreatedClientName = "resource-server"
  437. const serverState = getOrCreateClientState("resource-server")
  438. serverState.resources = [{ name: "my-resource", uri: "file:///test.txt", description: "A test resource" }]
  439. yield* mcp.add("resource-server", {
  440. type: "local",
  441. command: ["echo", "test"],
  442. })
  443. const resources = yield* mcp.resources()
  444. expect(Object.keys(resources).length).toBe(1)
  445. const key = Object.keys(resources)[0]
  446. expect(key).toContain("resource-server")
  447. expect(key).toContain("my-resource")
  448. }),
  449. ),
  450. )
  451. test(
  452. "prompts() skips disconnected servers",
  453. withInstance(
  454. {
  455. "prompt-disc-server": {
  456. type: "local",
  457. command: ["echo", "test"],
  458. },
  459. },
  460. (mcp) =>
  461. Effect.gen(function* () {
  462. lastCreatedClientName = "prompt-disc-server"
  463. const serverState = getOrCreateClientState("prompt-disc-server")
  464. serverState.prompts = [{ name: "hidden-prompt", description: "Should not appear" }]
  465. yield* mcp.add("prompt-disc-server", {
  466. type: "local",
  467. command: ["echo", "test"],
  468. })
  469. yield* mcp.disconnect("prompt-disc-server")
  470. const prompts = yield* mcp.prompts()
  471. expect(Object.keys(prompts).length).toBe(0)
  472. }),
  473. ),
  474. )
  475. // ========================================================================
  476. // Test: connect() on nonexistent server
  477. // ========================================================================
  478. test(
  479. "connect() on nonexistent server does not throw",
  480. withInstance({}, (mcp) =>
  481. Effect.gen(function* () {
  482. // Should not throw
  483. yield* mcp.connect("nonexistent")
  484. const status = yield* mcp.status()
  485. expect(status["nonexistent"]).toBeUndefined()
  486. }),
  487. ),
  488. )
  489. // ========================================================================
  490. // Test: disconnect() on nonexistent server
  491. // ========================================================================
  492. test(
  493. "disconnect() on nonexistent server does not throw",
  494. withInstance({}, (mcp) =>
  495. Effect.gen(function* () {
  496. yield* mcp.disconnect("nonexistent")
  497. // Should complete without error
  498. }),
  499. ),
  500. )
  501. // ========================================================================
  502. // Test: tools() with no MCP servers configured
  503. // ========================================================================
  504. test(
  505. "tools() returns empty when no MCP servers are configured",
  506. withInstance({}, (mcp) =>
  507. Effect.gen(function* () {
  508. const tools = yield* mcp.tools()
  509. expect(Object.keys(tools).length).toBe(0)
  510. }),
  511. ),
  512. )
  513. // ========================================================================
  514. // Test: connect failure during create()
  515. // ========================================================================
  516. test(
  517. "server that fails to connect is marked as failed",
  518. withInstance(
  519. {
  520. "fail-connect": {
  521. type: "local",
  522. command: ["echo", "test"],
  523. },
  524. },
  525. (mcp) =>
  526. Effect.gen(function* () {
  527. lastCreatedClientName = "fail-connect"
  528. getOrCreateClientState("fail-connect")
  529. connectShouldFail = true
  530. connectError = "Connection refused"
  531. yield* mcp.add("fail-connect", {
  532. type: "local",
  533. command: ["echo", "test"],
  534. })
  535. const status = yield* mcp.status()
  536. expect(status["fail-connect"]?.status).toBe("failed")
  537. if (status["fail-connect"]?.status === "failed") {
  538. expect(status["fail-connect"].error).toContain("Connection refused")
  539. }
  540. // No tools should be available
  541. const tools = yield* mcp.tools()
  542. expect(Object.keys(tools).length).toBe(0)
  543. }),
  544. ),
  545. )
  546. // ========================================================================
  547. // Bug #5: McpOAuthCallback.cancelPending uses wrong key
  548. // ========================================================================
  549. test("McpOAuthCallback.cancelPending is keyed by mcpName but pendingAuths uses oauthState", async () => {
  550. const { McpOAuthCallback } = await import("../../src/mcp/oauth-callback")
  551. // Register a pending auth with an oauthState key, associated to an mcpName
  552. const oauthState = "abc123hexstate"
  553. const callbackPromise = McpOAuthCallback.waitForCallback(oauthState, "my-mcp-server")
  554. // cancelPending is called with mcpName — should find the entry via reverse index
  555. McpOAuthCallback.cancelPending("my-mcp-server")
  556. // The callback should still be pending because cancelPending looked up
  557. // "my-mcp-server" in a map keyed by "abc123hexstate"
  558. let resolved = false
  559. let rejected = false
  560. callbackPromise.then(() => (resolved = true)).catch(() => (rejected = true))
  561. // Give it a tick
  562. await new Promise((r) => setTimeout(r, 50))
  563. // cancelPending("my-mcp-server") should have rejected the pending callback
  564. expect(rejected).toBe(true)
  565. await McpOAuthCallback.stop()
  566. })
  567. // ========================================================================
  568. // Test: multiple tools from same server get correct name prefixes
  569. // ========================================================================
  570. test(
  571. "tools() prefixes tool names with sanitized server name",
  572. withInstance(
  573. {
  574. "my.special-server": {
  575. type: "local",
  576. command: ["echo", "test"],
  577. },
  578. },
  579. (mcp) =>
  580. Effect.gen(function* () {
  581. lastCreatedClientName = "my.special-server"
  582. const serverState = getOrCreateClientState("my.special-server")
  583. serverState.tools = [
  584. { name: "tool-a", description: "Tool A", inputSchema: { type: "object", properties: {} } },
  585. { name: "tool.b", description: "Tool B", inputSchema: { type: "object", properties: {} } },
  586. ]
  587. yield* mcp.add("my.special-server", {
  588. type: "local",
  589. command: ["echo", "test"],
  590. })
  591. const tools = yield* mcp.tools()
  592. const keys = Object.keys(tools)
  593. // Server name dots should be replaced with underscores
  594. expect(keys.some((k) => k.startsWith("my_special-server_"))).toBe(true)
  595. // Tool name dots should be replaced with underscores
  596. expect(keys.some((k) => k.endsWith("tool_b"))).toBe(true)
  597. expect(keys.length).toBe(2)
  598. }),
  599. ),
  600. )
  601. // ========================================================================
  602. // Test: transport leak — local stdio timeout (#19168)
  603. // ========================================================================
  604. test(
  605. "local stdio transport is closed when connect times out (no process leak)",
  606. withInstance({}, (mcp) =>
  607. Effect.gen(function* () {
  608. lastCreatedClientName = "hanging-server"
  609. getOrCreateClientState("hanging-server")
  610. connectShouldHang = true
  611. const addResult = yield* mcp.add("hanging-server", {
  612. type: "local",
  613. command: ["node", "fake.js"],
  614. timeout: 100,
  615. })
  616. const serverStatus = (addResult.status as any)["hanging-server"] ?? addResult.status
  617. expect(serverStatus.status).toBe("failed")
  618. expect(serverStatus.error).toContain("timed out")
  619. // Transport must be closed to avoid orphaned child process
  620. expect(transportCloseCount).toBeGreaterThanOrEqual(1)
  621. }),
  622. ),
  623. )
  624. // ========================================================================
  625. // Test: transport leak — remote timeout (#19168)
  626. // ========================================================================
  627. test(
  628. "remote transport is closed when connect times out",
  629. withInstance({}, (mcp) =>
  630. Effect.gen(function* () {
  631. lastCreatedClientName = "hanging-remote"
  632. getOrCreateClientState("hanging-remote")
  633. connectShouldHang = true
  634. const addResult = yield* mcp.add("hanging-remote", {
  635. type: "remote",
  636. url: "http://localhost:9999/mcp",
  637. timeout: 100,
  638. oauth: false,
  639. })
  640. const serverStatus = (addResult.status as any)["hanging-remote"] ?? addResult.status
  641. expect(serverStatus.status).toBe("failed")
  642. // Transport must be closed to avoid leaked HTTP connections
  643. expect(transportCloseCount).toBeGreaterThanOrEqual(1)
  644. }),
  645. ),
  646. )
  647. // ========================================================================
  648. // Test: transport leak — failed remote transports not closed (#19168)
  649. // ========================================================================
  650. test(
  651. "failed remote transport is closed before trying next transport",
  652. withInstance({}, (mcp) =>
  653. Effect.gen(function* () {
  654. lastCreatedClientName = "fail-remote"
  655. getOrCreateClientState("fail-remote")
  656. connectShouldFail = true
  657. connectError = "Connection refused"
  658. const addResult = yield* mcp.add("fail-remote", {
  659. type: "remote",
  660. url: "http://localhost:9999/mcp",
  661. timeout: 5000,
  662. oauth: false,
  663. })
  664. const serverStatus = (addResult.status as any)["fail-remote"] ?? addResult.status
  665. expect(serverStatus.status).toBe("failed")
  666. // Both StreamableHTTP and SSE transports should be closed
  667. expect(transportCloseCount).toBeGreaterThanOrEqual(2)
  668. }),
  669. ),
  670. )