Skip to content

Fix intermittent missing enabled servers in tool retrieval - #446

Merged
Dumbris merged 2 commits into
smart-mcp-proxy:mainfrom
JasonLandbridge:server-discovery-fix
May 5, 2026
Merged

Dumbris merged 2 commits into
smart-mcp-proxy:mainfrom
JasonLandbridge:server-discovery-fix

Conversation

@JasonLandbridge

Copy link
Copy Markdown
Contributor

Summary

This PR fixes an intermittent issue where tools from enabled/connected servers (notably rider-official) would sometimes not appear in retrieve_tools results, even though upstream ListTools calls succeeded.

The fix addresses two core causes:

  1. Concurrent ListTools contention produced transient failures (ListTools operation already in progress) during discovery.
  2. Discovery race windows could temporarily omit connected servers from global discovery output, causing visible tool-set shrink in search results.

Root cause

During server churn (restart/reconnect, reactive discovery, background discovery), multiple discovery paths could call ListTools on the same managed client at the same time.

Previously:

  • first call proceeded,
  • second call failed fast with an “already in progress” error.

At the same time, global discovery accepted partial results from currently successful servers. If one connected server was omitted in that cycle, its tools were temporarily absent from indexed/searchable results.

This produced the observed “sometimes shows, sometimes missing” behavior.


What changed

1) Coalesced concurrent ListTools calls

File: internal/upstream/managed/client.go

  • Reworked managed client ListTools concurrency behavior:
    • one caller performs upstream ListTools,
    • concurrent callers wait for the same in-flight operation,
    • all waiters receive the shared result/error.
  • Eliminates fail-fast path that previously returned:
    • ListTools operation already in progress for server ...

Impact: prevents transient per-server tool discovery drops caused by local concurrency collisions.


2) Added last-good per-server snapshot fallback in global discovery

Files: internal/runtime/runtime.go, internal/runtime/lifecycle.go

  • Added runtime cache of last known good tool snapshots per server.
  • During DiscoverAndIndexTools:
    • fresh per-server snapshots are updated from current discovery results,
    • standard differential updates are applied,
    • for connected servers missing from the current discovery pass, the last-good snapshot is reused and re-applied.

Impact: avoids temporary index shrink when a connected server is missed in one discovery cycle.


3) Regression tests for ListTools coalescing

File: internal/upstream/managed/listtools_coalescing_test.go

Added tests:

  • TestListTools_CoalescesWaiters
  • TestListTools_CoalescesWaitersError

These verify that waiters receive shared success/error instead of being rejected while a list operation is already in progress.


Verification

  • go test ./internal/upstream/managed ./internal/runtime passed.
  • Build check passed (build_project success).

Scope and non-goals

  • This PR focuses on correctness/stability of discovery and visibility.
  • Does not change retrieval ranking semantics or hard limits (e.g., retrieve_tools.limit max 100).
  • Does not introduce debounce/metadata enhancements (can be follow-up).

Expected behavior after fix

  • Enabled/connected servers should no longer disappear from tool retrieval due to in-process ListTools races.
  • Transient discovery omissions should be masked by last-good snapshots, reducing inconsistent tool visibility across adjacent queries.

Follow-ups (optional)

  • Add explicit discovery health metadata to retrieve_tools responses (fresh/degraded, missing/stale servers).
  • Add event debounce for server churn bursts to reduce redundant discovery passes.
  • Add broader integration test simulating reconnect storms with repeated retrieval queries.

JasonLandbridge and others added 2 commits May 4, 2026 01:23
…t lifecycle

Address review feedback on PR smart-mcp-proxy#446:

1. acquireListToolsContext now ALWAYS allocates listToolsWaitCh and resets
   the cached last-result when electing a leader. Previously the helper was
   used by the health-check (client.go:750) and tool-count refresh
   (client.go:1224) without setting up a wait channel, so a concurrent
   ListTools waiter would block on a nil channel for up to 30s
   (ctx.Done()) instead of being unblocked when the holder finished.

2. The two non-coalescing callers (health check, tool-count refresh) now
   call publishListToolsResult so any ListTools waiter coalesced behind
   them receives the real tools list rather than nil/stale data.

3. ListTools is split into a leader path (runListToolsAsLeader) that goes
   through acquireListToolsContext and a wait path that loops on a
   genuine race (rare: holder released between the failed acquire and the
   re-check) before parking on the wait channel. Single source of truth
   for leader bookkeeping.

4. Runtime: prune r.lastGoodTools entries for servers no longer in
   GetAllServerNames() to prevent unbounded growth on config churn.

5. Demote the "reusing last-good tool snapshot" log from Warn to Info -
   it's benign self-healing that can fire repeatedly during reconnect
   storms and was noisy.

6. New regression tests in listtools_coalescing_test.go:
   - TestListTools_MultipleWaitersUnblockedByLeader: real
     leader/multi-waiter goroutine interaction.
   - TestListTools_HealthCheckLeaderDoesNotDeadlockWaiters: directly
     reproduces the nil-channel hang the old code allowed.
   - TestListTools_LeaderErrorPropagatedToWaiters: error fan-out.
   - TestListTools_AcquireContextResetsCachedResult: leader election
     clears stale per-call state.

Tests pass with -race on internal/upstream/managed and internal/runtime.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Dumbris

Dumbris commented May 4, 2026

Copy link
Copy Markdown
Member

Pushed 0fdbc4d8 addressing the review. Summary of changes:

1. Fixed nil-channel deadlock for non-ListTools leaders

acquireListToolsContext is still used by the health check (client.go:817) and the tool-count refresh (client.go:1290), but in the previous version of this PR it didn't allocate listToolsWaitCh. If either of those held the in-progress flag and a ListTools call arrived, the new waiter loop did:

waitCh := mc.listToolsWaitCh   // nil
select {
case <-ctx.Done():
case <-waitCh:                 // nil channel — blocks forever
}

That would hang for the full 30s ListTools timeout on every coalesced call, strictly worse than the old fail-fast.

Fix: acquireListToolsContext always allocates the wait channel and clears the cached result on leader election; both non-coalescing call sites now call the new publishListToolsResult helper before release() so any coalesced ListTools waiter gets a real result instead of nil/stale data.

2. Consolidated leader bookkeeping

ListTools was duplicating the leader-acquire logic from acquireListToolsContext. It now goes through that helper for the leader path (runListToolsAsLeader) — single source of truth for inProgress / waitCh / cancel lifecycle. The waiter loop handles the genuine race where the previous holder releases between our failed acquire and the re-check (rare, but possible) by retrying once before parking on the channel.

3. Snapshot map no longer grows unboundedly

DiscoverAndIndexTools now prunes r.lastGoodTools entries for servers no longer in GetAllServerNames(). Previously a removed/renamed server's snapshot lingered for the lifetime of the process.

4. Demoted self-healing log to Info

"Server missing from discovery result; reusing last-good tool snapshot" is benign self-healing and can fire repeatedly during reconnect storms — switched from Warn to Info.

5. Real concurrency tests

The original two tests in listtools_coalescing_test.go only exercised the waiter-reads-cached-result branch (preset state, then call ListTools). They never proved the leader path or the channel close ordering. Added:

  • TestListTools_MultipleWaitersUnblockedByLeader — real leader + 5 waiter goroutines, verifies all wake up and see the same published result.
  • TestListTools_HealthCheckLeaderDoesNotDeadlockWaiters — explicit regression test for the nil-channel bug. Spins a ListTools waiter behind a health-check style leader (acquired via acquireListToolsContext + publishListToolsResult) with a 2s ctx timeout. Fails the suite with "ListTools waiter did not wake up after leader released" if coalescing is broken.
  • TestListTools_LeaderErrorPropagatedToWaiters — error fan-out.
  • TestListTools_AcquireContextResetsCachedResult — guarantees a new leader election can never return stale data from a previous round.

Verification

go test ./internal/upstream/managed/ ./internal/runtime/ -race -count=1
ok      .../internal/upstream/managed   1.372s
ok      .../internal/runtime            90.053s
go build ./...   # clean

The ToolMetadata shallow-copy point from the review is left as-is (with a comment noting the immutability assumption); converting to a deep copy would touch a wider surface and the values aren't mutated post-discovery today.

@Dumbris
Dumbris merged commit cf14cb0 into smart-mcp-proxy:main May 5, 2026
22 checks passed
@Dumbris

Dumbris commented May 5, 2026

Copy link
Copy Markdown
Member

Thanks @JasonLandbridge! Merged. Solid root-cause work on the discovery race - the coalescing primitive is now the single source of truth for in-flight ListTools calls, which makes the next round of upstream-management changes a lot easier to reason about.

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.

3 participants