Skip to content

feat(mcp): reconnect client session on connection drop (#177) - #191

Merged
JAORMX merged 2 commits into
mainfrom
feat/mcp-reconnect-177
Jun 25, 2026
Merged

JAORMX merged 2 commits into
mainfrom
feat/mcp-reconnect-177

Conversation

@JAORMX

@JAORMX JAORMX commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #177.

When a remote MCP server's session drops mid-session — the server restarts (losing its in-memory session map), returns HTTP 404 "session not found", or closes the transport — the harness now transparently re-establishes the session and retries the call once, instead of hard-failing every subsequent MCP call and requiring a full session restart.

The design

  • Reconnect lives on *Server, which owns the session lifecycle and now retains the ServerConfig + httpClient + diag needed to rebuild the transport (dial extracted from Connect).
  • remoteTool holds *Server (not a raw *ClientSession) and calls through Server.withSession — the single retry shape shared by tool.Execute, readResource, and getPrompt.
  • Error class (isConnectionDrop): errors.Is the SDK's ErrConnectionClosed / ErrSessionMissing plus string-match for the unexported sentinels ("session not found", "client is closing", "connection closed", "connection refused").
  • Serialized reconnect: one dial under s.mu via a stale-session CAS — N concurrent failing calls produce exactly ONE dial.
  • Bounded: one reconnect + one retry per call. A permanently-down server surfaces a clear "unavailable after reconnect" tool error, never a raw transport string.
  • Close is terminal (a separate closed flag, distinct from dropped the retry flag): a post-close or racing in-flight call never dials and cannot resurrect a closed server.
  • No tool-list re-fetch on reconnect (session-swap preserves catalog registration; same as the v1 snapshot contract).
  • Breaker deliberately deferred (ADR 0056): the one-attempt bound already prevents masking a permanently-down server.

Review

Ran the dev-pipeline: architect → implementer → panel review (spec + standards + secure-code-reviewer + software-architect + QA) → iterate → commit. Two cross-confirmed ship-blockers from the panel were fixed in iteration 2:

  • Close not terminal (secure-code-reviewer + software-architect): a racing in-flight call could resurrect a closed server. Fixed by splitting dropped (clearable retry flag) from closed (terminal Close-only flag), with a top-of-reconnect check.
  • Clear-error requirement (spec axis): the genuinely-down server path leaked raw transport strings. Fixed with an errReconnectFailed sentinel mapped to the clear message at both tool.Execute and readResourceTool.Execute.

QA test-adequacy gaps closed: readResource/getPrompt reconnect tests, a load-bearing CAS-skip concurrency test, TestCallAfterCloseDoesNotDial, reconnect-then-retry-fails-non-drop, IsError-doesn't-trigger-reconnect, and diag-count asserts on the permanently-down test.

Files

  • internal/adapter/mcp/reconnect.go (new) — classifier, liveSession, reconnect (stale-session CAS + terminal closed check), withSession, sentinels.
  • internal/adapter/mcp/mcp.go — Server retains cfg/diag/httpClient + mu/dropped/closed; dial extracted; Close sets closed.
  • internal/adapter/mcp/tool.go — remoteTool holds *Server; Execute routes through withSession.
  • internal/adapter/mcp/resource.go / prompt.go — readResource/getPrompt via withSession.
  • internal/adapter/mcp/restool.go — clear-error mapping on readResourceTool.Execute.
  • internal/adapter/mcp/reconnect_test.go (new) — restartableServer fixture + 9 tests.
  • docs/adr/0056-mcp-client-reconnect.md (new), docs/design/PRODUCTION-READINESS.md, docs/architecture/extensibility.md, llms.txt (regenerated).

Verification

  • task lint && task test green (full suite, -race, api:check, docs:check).
  • go test -race -count=3 ./internal/adapter/mcp/... green.
  • go run ./cmd/mecademo prints a full offline session.
  • task generate run; llms.txt regenerated.

Checklist

  • Code follows the layering rule (internal/adapter/mcp imports only engine/port, engine/session, engine/tool + SDK + stdlib)
  • Diagnostics flow through port.Diagnostics (no slog in engine/ or internal/)
  • No stdio MCP (streaming-HTTP only)
  • Tests are offline (httptest + in-process MCP server); -race clean
  • Docs synced (ADR 0056, PRODUCTION-READINESS, architecture, llms.txt)

When a remote MCP server's session drops mid-session (server restart loses
its session map, returns 404 "session not found", or closes the transport),
the harness now transparently re-establishes the session and retries the
call once, instead of hard-failing every subsequent MCP call and requiring
a full session restart.

The reconnect lives on *Server (which owns the session lifecycle and now
retains the ServerConfig + httpClient + diag to rebuild the transport).
remoteTool holds *Server instead of a raw *ClientSession and calls through
Server.withSession — the single retry shape shared by tool.Execute,
readResource, and getPrompt. A connection-drop error class
(isConnectionDrop: errors.Is the SDK's ErrConnectionClosed/ErrSessionMissing
plus string-match for the unexported sentinels) triggers exactly one
serialized reconnect (N concurrent failing calls produce ONE dial via a
stale-session CAS under s.mu), then one retry. A permanently-down server
surfaces a clear "unavailable after reconnect" tool error, never a raw
transport string. Close is terminal (a separate `closed` flag): a post-close
or racing in-flight call never dials and cannot resurrect a closed server.

A breaker is deliberately deferred (ADR 0056): the one-attempt bound already
prevents masking a permanently-down server; add a breaker only if field data
shows flapping-server latency.

Tests: restartableServer fixture (stable-URL listener swap) covering
reconnect-after-restart, permanently-down clear error (both reject-404 and
dial-failure paths), concurrent-calls-reconnect-once (CAS-skip is
load-bearing), call-after-close-does-not-dial, readResource/getPrompt
reconnect, reconnect-then-retry-fails-non-drop, IsError-does-not-trigger-
reconnect, and the classifier table. All pass under -race -count=3.

Docs: ADR 0056 (frozen), PRODUCTION-READINESS reliability row,
architecture/extensibility.md one-liner, llms.txt regenerated.

Closes #177
CI failed TestPermanentlyDownServerDialFailureClearError on Linux: a
hard-stopped server yields a TCP reset ("EOF") rather than "connection
refused", and the SDK wraps it as "rejected by transport" (its internal
ErrRejected marker for a transient transport failure). Neither was in
connectionDropSignatures, so isConnectionDrop returned false → no reconnect
→ the raw transport string leaked to the model (the spec's clear-error
requirement was violated on CI).

Both are genuine connection drops: the session is unusable and a reconnect
is the right response. Add them to the classifier. Table test gains the
exact CI error string as a case so the regression is pinned.
@JAORMX
JAORMX merged commit 60dd661 into main Jun 25, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP client: reconnect/restart session on connection drop instead of hard-failing

1 participant