From bd07fe6c9cf2a9c247d48063132528116a3af8cb Mon Sep 17 00:00:00 2001 From: Reuven Date: Mon, 4 May 2026 21:05:45 -0400 Subject: [PATCH] fix(ruvocal/mcp): skip SSE fallback on 4xx/5xx + rate-limit cooldown (closes #1741) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Symptom: when an upstream MCP server returns HTTP 429, ruvocal's clientPool.ts always falls back to SSE — which POSTs to the SAME endpoint and hits the SAME rate limit. Users saw: HTTP transport failed: Streamable HTTP error: Error POSTing to endpoint: Rate exceeded. SSE fallback failed: SSE error: Non-200 status code (429) Twice the wait, misleading message implying the SSE transport itself broke. Fix in src/lib/server/mcp/clientPool.ts: 1. Skip SSE fallback for definitive HTTP failures (4xx/5xx, except 408 which is recoverable). They will recur on the sibling transport. 2. Throw typed McpRateLimitedError on 429 with status, retryAfterMs, serverName fields — callers can build a friendly countdown UI. 3. Honor Retry-After header when upstream provides it (capped at 60s, default 5s). 4. Memoize the failure for the cooldown window so subsequent getClient calls short-circuit instead of pounding the upstream. Cooldown is cleared by evictFromPool() and drainPool(). Tests: 8 vitest cases in clientPool.spec.ts cover skip-on-429, Retry-After honor, cooldown memoization, skip-on-401/503, fallback on network/408, and 429 surfaced even when both transports report it. 8/8 pass. Issue: ruvnet/ruflo#1741 Co-Authored-By: RuFlo --- .../src/lib/server/mcp/clientPool.spec.ts | 175 ++++++++++++++++++ .../ruvocal/src/lib/server/mcp/clientPool.ts | Bin 2252 -> 8014 bytes 2 files changed, 175 insertions(+) create mode 100644 ruflo/src/ruvocal/src/lib/server/mcp/clientPool.spec.ts diff --git a/ruflo/src/ruvocal/src/lib/server/mcp/clientPool.spec.ts b/ruflo/src/ruvocal/src/lib/server/mcp/clientPool.spec.ts new file mode 100644 index 0000000000..29ba368d3c --- /dev/null +++ b/ruflo/src/ruvocal/src/lib/server/mcp/clientPool.spec.ts @@ -0,0 +1,175 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; + +// We mock the MCP SDK transports + Client so we can drive the connection +// outcomes deterministically. The point of these tests is to verify that +// clientPool.ts: +// 1. Skips the SSE fallback when the first transport returns 4xx/5xx (e.g. 429) +// because retrying via SSE will hit the same upstream and produce the +// same rate-limit response. +// 2. Surfaces a typed McpRateLimitedError on 429 with retryAfterMs derived +// from the upstream Retry-After header when present. +// 3. Memoizes the failure for a cooldown window so subsequent getClient +// calls don't pound the upstream. +// 4. Still falls back to SSE for transport-level / network errors that +// have no HTTP status (the "Streamable HTTP server is not running" path). + +const httpConnectMock = vi.fn(); +const sseConnectMock = vi.fn(); + +vi.mock("@modelcontextprotocol/sdk/client", () => { + class MockClient { + private nextTransportIsHttp = true; + async connect(transport: unknown) { + // The transport instances are tagged below in the streamableHttp/sse mocks. + const isHttp = (transport as { __kind?: string }).__kind === "http"; + if (isHttp) { + return httpConnectMock(); + } + return sseConnectMock(); + } + async close() {} + async callTool() { + return { content: [] }; + } + } + return { Client: MockClient }; +}); + +vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => { + class StreamableHTTPError extends Error { + code: number; + constructor(code: number, message: string) { + super(`Streamable HTTP error: ${message}`); + this.code = code; + this.name = "StreamableHTTPError"; + } + } + class StreamableHTTPClientTransport { + __kind = "http"; + constructor(_url: URL, _opts: unknown) {} + } + return { StreamableHTTPError, StreamableHTTPClientTransport }; +}); + +vi.mock("@modelcontextprotocol/sdk/client/sse.js", () => { + class SSEClientTransport { + __kind = "sse"; + constructor(_url: URL, _opts: unknown) {} + } + return { SSEClientTransport }; +}); + +// Import AFTER vi.mock declarations. +import { getClient, drainPool, McpRateLimitedError } from "./clientPool"; + +const server = { name: "test-server", url: "https://example.test/mcp", headers: {} }; + +describe("clientPool — rate-limit and HTTP error handling", () => { + beforeEach(async () => { + await drainPool(); + httpConnectMock.mockReset(); + sseConnectMock.mockReset(); + }); + + afterEach(async () => { + await drainPool(); + }); + + it("skips SSE fallback on 429 and throws McpRateLimitedError", async () => { + httpConnectMock.mockRejectedValue( + new StreamableHTTPError( + 429, + "Error POSTing to endpoint: Rate exceeded. Retry-After: 7" + ) + ); + + await expect(getClient(server)).rejects.toBeInstanceOf(McpRateLimitedError); + // Critical: SSE was NOT attempted — would just hit the same upstream. + expect(sseConnectMock).not.toHaveBeenCalled(); + expect(httpConnectMock).toHaveBeenCalledTimes(1); + }); + + it("honors Retry-After when present in the error message", async () => { + httpConnectMock.mockRejectedValue( + new StreamableHTTPError( + 429, + "Error POSTing to endpoint: Rate exceeded. Retry-After: 12" + ) + ); + + try { + await getClient(server); + throw new Error("should have thrown"); + } catch (err) { + expect(err).toBeInstanceOf(McpRateLimitedError); + expect((err as McpRateLimitedError).retryAfterMs).toBe(12_000); + expect((err as McpRateLimitedError).status).toBe(429); + expect((err as McpRateLimitedError).serverName).toBe("test-server"); + } + }); + + it("memoizes the 429 failure and skips network on subsequent calls during cooldown", async () => { + httpConnectMock.mockRejectedValue( + new StreamableHTTPError(429, "Error POSTing to endpoint: Rate exceeded. Retry-After: 5") + ); + + await expect(getClient(server)).rejects.toBeInstanceOf(McpRateLimitedError); + // Second call within the cooldown window: must NOT touch the upstream again. + await expect(getClient(server)).rejects.toBeInstanceOf(McpRateLimitedError); + expect(httpConnectMock).toHaveBeenCalledTimes(1); + expect(sseConnectMock).not.toHaveBeenCalled(); + }); + + it("skips SSE fallback on 4xx (e.g. 401)", async () => { + httpConnectMock.mockRejectedValue( + new StreamableHTTPError(401, "Unauthorized") + ); + await expect(getClient(server)).rejects.toThrow(/HTTP 401/); + expect(sseConnectMock).not.toHaveBeenCalled(); + }); + + it("skips SSE fallback on 5xx (e.g. 503)", async () => { + httpConnectMock.mockRejectedValue( + new StreamableHTTPError(503, "Service Unavailable") + ); + await expect(getClient(server)).rejects.toThrow(/HTTP 503/); + expect(sseConnectMock).not.toHaveBeenCalled(); + }); + + it("falls back to SSE on transport-level / network errors with no HTTP status", async () => { + httpConnectMock.mockRejectedValue(new Error("ECONNREFUSED")); + sseConnectMock.mockResolvedValue(undefined); + + const client = await getClient(server); + expect(client).toBeDefined(); + expect(httpConnectMock).toHaveBeenCalledTimes(1); + expect(sseConnectMock).toHaveBeenCalledTimes(1); + }); + + it("falls back to SSE on 408 Request Timeout (recoverable)", async () => { + httpConnectMock.mockRejectedValue( + new StreamableHTTPError(408, "Request Timeout") + ); + sseConnectMock.mockResolvedValue(undefined); + + const client = await getClient(server); + expect(client).toBeDefined(); + expect(sseConnectMock).toHaveBeenCalledTimes(1); + }); + + it("surfaces 429 even when the SSE fallback also reports 429", async () => { + httpConnectMock.mockRejectedValue(new Error("transport mismatch")); // forces SSE attempt + sseConnectMock.mockRejectedValue( + new Error("SSE error: Non-200 status code (429)") + ); + + try { + await getClient(server); + throw new Error("should have thrown"); + } catch (err) { + expect(err).toBeInstanceOf(McpRateLimitedError); + expect((err as McpRateLimitedError).status).toBe(429); + } + }); +}); diff --git a/ruflo/src/ruvocal/src/lib/server/mcp/clientPool.ts b/ruflo/src/ruvocal/src/lib/server/mcp/clientPool.ts index 2f78ddd9a394fb007b1f930f2edc73a0b9137286..52fdf131df17ff584a337430f12a69b9a4cc4611 100644 GIT binary patch literal 8014 zcmcIp|8CpJ5$?azQ_Km*9hJzGlI9Mr93?dz2MHR-f#t&$NP>taR~BQ5WVw_jS5eW2 z=o9uy`pxVvN&RpxcW4j6LFO)JXJ%)<`DPf;vNSJfMJLl(B?YZ%oToEt{biO$Y8s|V zp_WCKr$rj3)2@zgx}j`r9W`V7YO^scauv*itEqZ*dHK#ry3B(_v+U0H`e~l0d8hfU zCv|lty(lvOv#y;@!{O=HdEab8S8KH)t+>k+JaHCgLzUmE{3K1r@pUQB?@n;OISnc_ z;T&C1mZno0P@)!e7GzJMY@A$otUI51ZEWm5c+jK=bb_5xx=3i8=A@D+OXH-_R7`?` za#hUpL`4)(k|u}vGrwbh5<8T15fpPxp7O7Kdh+(n8VM3AT#n zq=P$6tvtZfX*`Py6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