typescript-utcp icon indicating copy to clipboard operation
typescript-utcp copied to clipboard

@utcp/mcp: cached session never evicted on auth errors (401) — dead transport accumulates abort listeners (MaxListenersExceededWarning)

Open h3xxit opened this issue 4 months ago • 1 comments

Summary

In @utcp/mcp (1.1.3), a cached MCP session whose server rejects requests with an auth error (e.g. HTTP 401 from an expired OAuth token) is never evicted from the session cache. Every subsequent registerManual/tool call reuses the same dead StreamableHTTPClientTransport, fails again, and each failed send adds another abort listener to the transport's lifetime AbortController signal. In a long-running server that rebuilds UTCP clients regularly, this produces an unbounded listener build-up:

(node:18) MaxListenersExceededWarning: Possible EventTarget memory leak detected.
1779 abort listeners added to [AbortSignal]. MaxListeners is 1500. Use events.setMaxListeners() to increase limit

alongside an endless loop of:

[McpCommunicationProtocol] Reusing existing MCP session for 'notion:http'.
[McpCommunicationProtocol Error] MCP operation on 'notion:http' failed: Streamable HTTP error: Error POSTing to endpoint: {"error":"invalid_token","error_description":"Invalid access token"}

Mechanism

In McpCommunicationProtocol._withSession (dist/index.cjs ~4317), the cleanup-and-retry path only triggers for a hard-coded allow-list of error substrings:

if (errorMsg.includes("closed") || errorMsg.includes("disconnected") ||
    errorMsg.includes("econnreset") || errorMsg.includes("etimedout") ||
    errorMsg.includes("already initialized")) {
  await this._cleanupSession(sessionKey);
  ...
}
throw e;

An auth failure (StreamableHTTPError with code: 401, message invalid_token / Session expired) matches none of these, so the broken session object stays in _mcpSessions (keyed serverName:transport) indefinitely. _getOrCreateSession then logs "Reusing existing MCP session" and hands back the same dead transport forever.

Because the MCP SDK's StreamableHTTPClientTransport uses one AbortController for its lifetime and registers an abort listener per outgoing request, every failed reuse leaks one more listener on that single signal — the transport is never closed, so they are never released.

Two secondary aggravators:

  1. Promise.race([operation(client), timeoutPromise]) abandons the losing operation without aborting it — a timed-out operation keeps running (and keeps its listener) against the cached client.
  2. There is no failure back-off: a manual with a permanently broken credential is re-dialed on every client build.

Reproduction sketch

  1. Register an mcp call template with transport: "http" pointing at any streamable-HTTP MCP server behind OAuth.
  2. Let the token expire (or supply an invalid one).
  3. In a loop, create a UtcpClient and call registerManual for that template (simulating a server that builds one client per session).
  4. Observe: every iteration logs "Reusing existing MCP session" + the 401, and process.on('warning') fires MaxListenersExceededWarning with a monotonically growing listener count on the same AbortSignal.

Suggested fix

  • Evict the cached session (_cleanupSession) on auth-shaped failures too — e.g. any StreamableHTTPError with code 401/403, or more robustly: evict on any error thrown by transport-level send (as opposed to tool-level JSON-RPC errors), rather than substring-matching messages.
  • Optionally: abort the losing branch of the Promise.race timeout so abandoned operations release their resources.
  • Optionally: a short-TTL failure memo per session key to avoid re-dialing a known-broken server on every client build (we implemented exactly this downstream as a workaround, which stops the listener growth in practice).

Environment

  • @utcp/mcp 1.1.3, @utcp/sdk 1.1.1, @utcp/code-mode 1.2.12
  • @modelcontextprotocol/sdk 1.29.0
  • Node 22 (node:22-slim container), long-running Express server building one CodeModeUtcpClient per user session

h3xxit avatar Aug 04 '26 09:08 h3xxit

Update: we traced the same warning on a deployment where all cached sessions were healthy (no 401s) — the accumulation also happens through the SDK's standalone GET SSE stream, whose retry counter resets to zero on every graceful close, so hosted servers that politely close idle streams put each cached session into an infinite reconnect loop. Filed separately with the captured allocation stack and a workaround in #35; the two issues share the underlying shape (one transport-lifetime AbortSignal fed into every fetch, listeners released only at GC) but have independent triggers, so fixing one does not fix the other.

h3xxit avatar Aug 19 '26 13:08 h3xxit