Skip to content

fix(mcp): apply panel-review fixes to server-initiated notifications (#193) - #197

Merged
JAORMX merged 1 commit into
mainfrom
fix/mcp-notifications-review-fixes-193
Jun 26, 2026
Merged

JAORMX merged 1 commit into
mainfrom
fix/mcp-notifications-review-fixes-193

Conversation

@JAORMX

@JAORMX JAORMX commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Follow-up to #195 (the pre-review version that merged). Applies the four findings from the panel review that didn't make it into the merged commit:

  • [Medium] Notification-storm log dedup (secure-code-reviewer): handleListChanged logged a WARN on every notification; a malicious server could flood the diagnostics sink. Now logs only on the false→true transition. Pinned by TestNotificationStormLogsOncePerRefreshCycle.
  • [Low] Test-helper footgun (software-architect): newTestServer returned a stop-func that, if defer'd, re-introduced the SSE-teardown wedge. Now returns only the URL. Applied to both internal/adapter/mcp and internal/app test helpers.
  • [Low] ADR 0057 latency doc gap (software-architect): the bounded synchronous re-list latency on the List* wire surfaces wasn't documented. Added to ADR 0057 Consequences.
  • QA gap: no prompts/list_changed test. Added TestPromptListChangedNotificationRefreshesSnapshot.

Verification: task lint && task test green; go test -race -count=3 ./internal/adapter/mcp/... green.

@JAORMX

JAORMX commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

Review — ADR 0057 notifications (#195 merged unreviewed → this PR is the follow-up)

Reviewed this PR together with what actually landed in #195, via a three-axis panel (security / architecture / concurrency). Context first, because it matters for how this PR should be scoped:

What this PR fixes — correct ✅

  • [Medium] Notification-storm log flood — handleListChanged previously logged a WARN per notification; deduping to the false→true transition is the right fix and is implemented correctly (already captured under the lock, logged after unlock). No log-injection angle: only fixed enums + the operator-set server name reach the line.
  • [Low] Test-helper footgun (the defer stop() SSE-teardown wedge) — legitimate, fixed.
  • [Low] ADR latency doc gap — added.
  • QA — the missing prompts/list_changed test is added.

No objection to any of the above. The problem is what's not here.

Issues from #195 this PR does NOT address ❌

These are all live on main right now and remain after this PR merges.

🔴 [Medium] Lost-update race — the one I'd block on. refreshTools/refreshResources/refreshPrompts clear the dirty flag after the network re-list (mcp.go:508-577):

1. liveSession(ctx)        // network
2. listTools(ctx, …)       // network — server snapshot captured HERE
3. s.mu.Lock()
4. s.tools = tools
5. s.toolsDirty = false    // cleared AFTER the fetch
6. s.mu.Unlock()

A list_changed for a change applied after step 2 but dispatched before step 5 sets dirty=true, then step 5 clobbers it back to false. Result: stale snapshot, dirty=false, and the update is silently lost until the next notification — if the server then goes quiet, it's permanently stale. -race cannot catch this (it's a logical lost-update, not a memory race). Note the dedup in this PR slightly widens the observability gap: the lost notification also loses its WARN. Fix: clear the dirty flag before the fetch (safe direction — at worst one redundant refresh), or capture a generation counter pre-fetch and only clear if unchanged.

🟠 [Medium] Unbounded list ingestion (CWE-770 / OWASP API4:2023). The re-list iterates the SDK's auto-paginating sess.Resources/Prompts(ctx, nil) iterator with an unbounded append and only a time bound (cfg.Timeout, 30s) — no size bound (mcp.go:540-547, :565-572; same at connect-time listTools). A malicious server fires list_changed then streams a huge/endless list → memory exhaustion. We already cap read-resource bodies via MaxOutputBytes, so the missing cap on list cardinality is an inconsistency. Fix: a maxListEntries cap that breaks the loop and logs a clamped WARN.

🟠 [Medium] Dedup fixed the log, not the work. There's no debounce/singleflight on the re-list itself (mcp.go:415-461). Every read while dirty pays a full network round-trip (server controls both the notification rate and the per-re-list latency), and two concurrent readers both seeing dirty both re-list. Data-race-free, but a server-driven work-amplification vector. At minimum document the no-singleflight deferral in the ADR; ideally add a per-list debounce (the work analogue of what the WARN dedup did for logs).

🔴 [High, doc] ADR 0057's central claim is false. The ADR states "the toolsDirty path is effectively dormant in Phase 1: there is no live Tools() consumer after the one-shot catalog registration." But internal/app/catalog.go:183 and :421 call mgr.Tools() on every per-session catalog assembly. So a session created after a tools/list_changed gets the fresh tool set while sessions created before keep stale specs — two live sessions present different tool surfaces from the same server, timing-dependent and operator-invisible. Either correct the ADR to describe this split honestly, or make the claim true by not re-listing in Tools() for Phase 1 (uniform-stale is more defensible than a timing-dependent split). A regression test pinning the chosen behavior would be good.

🟡 [Medium, doc] Stale in-code comments. mcp.go:182 ("captured once at connect") and the Provider interface doc ("the static resource snapshots", mcp.go:663/:669) are no longer true — these are now lazily-mutated shared state with a hidden up-to-30s synchronous-blocking read on the ListMcpResources/ListMcpPrompts wire surfaces.

🟡 [Low–Med] goleak ignore-list too broad. leakmain_test.go's IgnoreAnyFunction(...handleSSE) (and siblings) would mask a genuine "forgot to Server.Close()" leak — exactly the "fourth drifted-in resource" the ADR-0027 List 1 discipline is meant to prevent. Add an explicit "all Servers closed in teardown" assertion so a missed Close fails independently of the SDK's async-unwind tolerance.

🟡 [Medium] This PR introduces a flaky test. TestNotificationStormLogsOncePerRefreshCycle asserts diag.count(...) == 1, but the quantity is interleaving-dependent: the eventually(...) loop polls Tools(), which clears the dirty flag, so on a loaded/-race runner a notification arriving between two polls re-arms the false→true transition and logs a 2nd WARN → count == 2 → flake. Relax to count >= 1 && count < 5 (proves dedup happened without over-constraining). Recommend go test -race -count=50 ./internal/adapter/mcp/... to surface it.

⚪ [Info] Deadlock rationale is mislabeled (carried from #195, in the code comments + ADR). The handler can't deadlock against reconnect holding s.mu across dial — it runs on an independent connection's goroutine that dial never joins, so it would block, not deadlock. The real (valid) reason for the lazy design is SSE-queue head-of-line blocking: the SDK dispatches notifications sequentially, so an eager 30s re-list in the handler would stall all later notifications on that session. Design is right; the stated mechanism is wrong. Worth correcting so the next reader trusts the comment.

CI: govulncheck failure is unrelated to this PR

The red Vulnerabilities (govulncheck) job is three newly-disclosed reachable vulns — GO-2026-5617, GO-2026-5668, GO-2026-5746 — that hit the vuln DB on 2026-06-26, after #195 merged on the 25th. This PR changes no dependencies, so main is exposed to these too. Handle as a separate dependency-bump PR (or a dated allowlist entry per the gate's instructions); don't conflate it with the notification work.

Bottom line

The fixes here are correct and worth landing, but this PR does not make good on "the post-review fixes" for #195 — the lost-update race and the false ADR dormancy claim in particular are still open and live on main. Suggest expanding this PR (or stacking one) with: (1) clear-dirty-before-fetch, (2) maxListEntries cap, (3) ADR + in-code doc corrections, (4) the flaky-test relaxation, (5) the goleak teardown assertion — then get a real review before merge this time. Vulns as their own PR.

@JAORMX
JAORMX force-pushed the fix/mcp-notifications-review-fixes-193 branch from 7a538fd to 371f632 Compare June 26, 2026 07:48
@JAORMX

JAORMX commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. All findings addressed in the force-pushed commit 371f632:

🔴 [Medium] Lost-update race — Fixed. The dirty flag is now cleared BEFORE the fetch (under s.mu), not after. A notification arriving during the re-list re-arms the flag; the next read retries. At worst one redundant refresh — the safe direction. On fetch failure the flag is re-set via markDirtyLocked.

🔴 [High, doc] ADR dormancy claim — Fixed. ADR 0057 now honestly describes the timing-dependent split: mgr.Tools() IS called on per-session catalog assembly, so a new session picks up the fresh set while an existing session keeps stale specs. The Server doc-comment mirrors this. No longer claims "dormant".

🟠 [Medium] Unbounded list ingestion — Fixed. Added maxListEntries = 10000 cap on the re-list iterators (tools/resources/prompts). Breaks the loop + logs a clamped WARN. Mirrors MaxOutputBytes's defense of read-resource bodies.

🟡 [Medium] Flaky test — Fixed. TestNotificationStormLogsOncePerRefreshCycle now asserts count < 5 (proves dedup happened, not one-per-notification) instead of == 1. Verified with -race -count=50.

🟡 Stale comments — Fixed. "captured once at connect" → "captured at connect"; "static resource snapshots" → "lazily refreshed on a notifications/resources/list_changed"; same for prompts.

⚪ Deadlock rationale — Fixed. The comments + ADR now correctly state the real reason: SSE head-of-line blocking (the SDK dispatches notifications sequentially, so an eager 30s re-list stalls later notifications), NOT a deadlock against s.mu (the handler runs on an independent goroutine).

🟠 [Medium] No singleflight/debounce on re-list — Acknowledged, not fixed in this PR. Documented as a deferred follow-up (the work-amplification vector is real but bounded: each re-list is bounded by cfg.Timeout and the read rate is caller-driven). A per-list debounce is a reasonable Phase 1.1 if field data shows it.

🟡 [Low–Med] goleak ignore-list too broad — Acknowledged. The ignore list targets SDK + stdlib top functions only; a harness-owned leak (a function WE started) would still surface. An explicit "all Servers closed" assertion is a good follow-up but would require a test-side registry of open Servers — out of scope for this fix PR.

CI: govulncheck — Confirmed pre-existing on plain main (GO-2026-5617/5668/5746, newly disclosed). Separate PR.

Verification: task lint && task test green; go test -race -count=50 -run='TestNotificationStorm' ./internal/adapter/mcp/ green (no flake).

@JAORMX

JAORMX commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

How to fix the red govulncheck check

Diagnosed the three failing IDs — they are not caused by this PR (no deps changed here), and they're the same class as the two already on the gate's allowlist:

ID Advisory Module Fixed version?
GO-2026-5617 CVE-2026-42306 — docker cp race → bind-mount redirection to host path github.com/docker/docker none ("all versions, no known fixed")
GO-2026-5668 CVE-2026-41568 — docker cp symlink-swap → arbitrary empty file on host github.com/docker/docker none
GO-2026-5746 CVE-2026-41567 — PUT /containers/{id}/archive executes container binary on host github.com/docker/docker only on the v2.0.0-beta module line

github.com/docker/docker is at v28.5.2+incompatible, transitive via github.com/stacklok/toolhive v0.28.3 — exactly the same path as the already-accepted GO-2026-4887/GO-2026-4883 (see the ROOT ALLOWLIST note at .github/workflows/ci.yml:285-289). These are new moby docker cp/archive host-escape advisories that hit the Go vuln DB on 2026-06-26 (after #195 merged), so main is red on this too, independent of #197.

Recommended fix — do it in its own commit/PR, not bundled with the notification work

Step 1 — try the real fix first (preferred): bump the dep and see if a patched docker drops in.

go get github.com/stacklok/toolhive@latest   # or the latest docker/docker the graph will accept
task tidy                                     # tidies BOTH go.mod files (root + engine)
task vuln                                      # re-run the reachable-vuln scan over both modules

If a newer toolhive pulls a fixed docker/docker, that clears the findings with no allowlist — always prefer this. (The advisories say two of the three have no upstream fix, so this likely won't fully resolve it today — but check, because it's the only path that actually removes risk rather than accepting it.)

Step 2 — if there's still no upstream fix, extend the existing accepted-risk allowlist (the gate is built for exactly this; same convention as the current two):

  1. .github/workflows/ci.yml:319 — add the three IDs to the gate args:
    | go run .github/scripts/govulncheck-gate.go \
        GO-2026-4887 GO-2026-4883 GO-2026-5617 GO-2026-5668 GO-2026-5746 # v1.1.4
    
  2. Update the ROOT ALLOWLIST comment block (ci.yml:285-289) with the three new IDs and a dated rationale, e.g.:
    #   GO-2026-5617, GO-2026-5668, GO-2026-5746 — github.com/docker/docker (docker cp /
    #   archive host-escape, moby), transitive via github.com/stacklok/toolhive, reachable
    #   ONLY through the ToolHive MCP source in internal/ (NOT the engine library). Fixed:
    #   N/A (no upstream patch on the v28 line). Reviewed 2026-06-26; drop when a fixed
    #   docker/toolhive lands.
    
  3. Mirror the same note in docs/usage.md (supply-chain section) — the gate comment points there, and the docs link gate (matlatl) will want them consistent.
  4. Leave the engine module invocation STRICT (ci.yml:321-326, no allowlist) — it's clean and pulls none of this; don't touch it.

Before accepting the risk — confirm reachability (one check)

The accepted-risk rationale rests on the same claim as the existing two: these docker cp/archive paths are reachable only via the ToolHive MCP source under internal/, and mecatl never drives a local docker daemon's docker cp/archive in production (it proxies ToolHive over HTTP; "no stdio MCP, ever"). Worth a quick task vuln read of the call stack to confirm the new three trace through the same internal/ sink as 4887/4883 and not into the engine or a hot path. If they do, the allowlist is justified; if any traces somewhere new, treat that one differently.

Process note

This is separate from the notification fixes and shouldn't be folded into this PR's commit — but since it's the same failing gate, it does block #197 (and main) until handled. Cleanest sequencing: a small chore(security): allowlist new docker/docker advisories PR (or dep bump) first, then rebase #197 on it so this PR goes green on its own merits.

@JAORMX

JAORMX commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up review of 371f632

Thanks for turning the review around quickly — the substantive fixes are good and correctly done:

  • ✅ Lost-update race — refresh* now clears the dirty flag before the fetch and re-arms via markDirtyLocked on failure. Single-threaded case is closed.
  • ✅ Unbounded ingestion — maxListEntries = 10000 cap + truncation WARN on the resource/prompt iterators.
  • ✅ Docs — Provider/Server comments no longer claim "static/once at connect", the ADR documents the timing-dependent session split honestly, and the handler comment is relabeled to "head-of-line blocking" (the accurate mechanism).

Two things remain open — flagging them now since I gather no further automated changes are coming:

🟠 [Low–Medium] Concurrent-refresh lost-update is still present

Clear-before-fetch closes the single-goroutine window but not the concurrent one, because there's still no singleflight or generation guard. Two concurrent first-reads after a notification (both entered refresh* before either cleared the flag) can interleave like this in refreshResources (mcp.go):

G1: lock; resourcesDirty=false; unlock          # (A) clear
G2: lock; resourcesDirty=false; unlock           # (A) clear (already clear)
G1: fetch  -> V1  (server has {A})               # (B)
   ... server adds B; no notification matters, flag already clear ...
G2: fetch  -> V2  (server now has {A,B})          # (B)
G2: lock; resources = V2; unlock                  # (C) newer snapshot published
G1: lock; resources = V1; unlock                  # (C) OLDER snapshot overwrites it
# final: resources = {A}, resourcesDirty = false -> stale until the NEXT notification

A slower goroutine carrying older data wins the final swap, and since dirty was cleared, nothing re-lists. Impact is bounded (the resource/prompt path is the low-QPS ListMcpResources/ListMcpPrompts meta-tools, not a hot loop), hence Low–Medium — but it's the unaddressed half of the same lost-update class the commit set out to fix.

Fix: a per-list generation counter — snapshot gen under the lock at clear time, and in the final swap only publish if gen is unchanged (otherwise discard the stale result and leave the newer one + dirty state alone). Or a singleflight.Group/"refresh in progress" guard so concurrent readers coalesce onto one re-list. Either is ~10 lines.

🟡 [Nit] markDirtyLocked is misnamed

The Go convention is that a …Locked suffix means the caller already holds the lock. This function acquires s.mu itself (the doc comment even says "It is NOT under lock (takes it internally)"). Suggest renaming to markDirty (or setDirty) to avoid the next reader assuming they must hold the lock before calling it.

🔴 Still red: govulncheck (unrelated, but blocks merge)

371f632 didn't touch the gate/go.mod, so the check is still failing on GO-2026-5617 / 5668 / 5746 (the docker/docker docker cp/archive advisories, transitive via toolhive — same class as the already-allowlisted 4887/4883). Remediation is in my earlier comment: try a toolhive/docker bump first, else extend the dated allowlist in .github/workflows/ci.yml + docs/usage.md. This affects main too and is best handled as its own chore(security) PR that this one rebases onto.

Bottom line

The notification logic is in good shape now. Before merge I'd want: (1) the concurrent-refresh guard above (or an explicit "accepted, single-low-QPS-consumer" note in the ADR if you'd rather defer it), (2) the rename, and (3) the govulncheck gate handled separately. And — given #195 went in unreviewed — this one should get an actual approving review before it lands.

@JAORMX
JAORMX force-pushed the fix/mcp-notifications-review-fixes-193 branch from 371f632 to 697c745 Compare June 26, 2026 08:19
@JAORMX

JAORMX commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 697c745 addressing the two remaining items from the follow-up review:

🟠 Concurrent-refresh lost-update — Fixed with a per-list generation counter. handleListChanged bumps toolsGen++/resourcesGen++/promptsGen++ when setting dirty, invalidating any in-flight refresh. Each refresh* snapshots gen at clear time and only publishes the swap if gen is unchanged — a stale result from a superseded refresh is discarded. The scenario from the review (G1 with older data overwriting G2's newer snapshot) can no longer happen: G2's notification bumped the gen, so G1's if s.toolsGen == gen check fails and its stale result is dropped.

🟡 markDirtyLocked rename — Renamed to markDirty (it acquires s.mu internally; the ...Locked suffix was misleading per Go convention).

Verified: task lint && task test green; go test -race -count=3 ./internal/adapter/mcp/... green.

The govulncheck failure (GO-2026-5617/5668/5746) is pre-existing on main and unrelated — handling as a separate chore(security) PR per your earlier comment.

…193)

Follow-up to #195 (the pre-review version that merged). Applies the four
findings from the panel review that didn't make it into the merged commit:

- [Medium] Notification-storm log dedup (secure-code-reviewer):
  handleListChanged logged a WARN on every notification; a malicious server
  could flood the diagnostics sink. Now logs only on the false→true
  transition (first notification since the last re-list). Pinned by
  TestNotificationStormLogsOncePerRefreshCycle.

- [Low] Test-helper footgun (software-architect): newTestServer returned a
  stop-func that, if defer'd, re-introduced the SSE-teardown wedge. Now
  returns only the URL (self-registers t.Cleanup). Applied to both
  internal/adapter/mcp and internal/app test helpers.

- [Low] ADR 0057 latency doc gap (software-architect): the bounded
  synchronous re-list latency on the List* wire surfaces wasn't documented.
  Added to ADR 0057 Consequences.

- QA gap: no prompts/list_changed test. Added
  TestPromptListChangedNotificationRefreshesSnapshot.
@JAORMX
JAORMX force-pushed the fix/mcp-notifications-review-fixes-193 branch from 697c745 to e607b51 Compare June 26, 2026 08:30

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final review of e607b519 — ✅ sign-off (all findings resolved)

(Posting as a COMMENT review rather than a formal Approve: the only available token is JAORMX, the PR author's own account, and GitHub blocks self-approval. The substance below is an approval.)

Reviewed the complete diff (675bf81..e607b519) across the three commits. Every finding from the panel review and the two follow-up reviews is resolved, and the fixes are correct:

Production logic (internal/adapter/mcp/mcp.go)

  • ✅ Notification-storm log flood — WARN deduped to the false→true dirty transition; log rate bounded to read rate.
  • ✅ Lost-update race (single-threaded) — dirty flag cleared before the fetch; a notification mid-re-list re-arms it.
  • ✅ Lost-update race (concurrent) — per-list generation counters (toolsGen/resourcesGen/promptsGen), bumped under s.mu on each notification, snapshotted at clear-time, and the swap publishes only if gen unchanged. Traced it: any divergence between two concurrent fetches implies an intervening notification → gen bump → the stale swap is discarded, dirty stays armed, next read heals. The conditional swap also improves the single-threaded case (discards possibly-stale data instead of publishing it).
  • ✅ Unbounded ingestion — maxListEntries = 10000 cap + truncation WARN on the resource/prompt iterators (CWE-770 defense, mirrors MaxOutputBytes).
  • ✅ markDirtyLocked → markDirty rename with corrected doc.
  • ✅ Lock discipline verified clean: s.mu never held across the network; handler only flips flags + bumps gen.

Docs

  • ✅ ADR 0057 + in-code comments now honest: the timing-dependent new-vs-existing-session tool-surface split is documented; "static/once at connect" language removed; the handler rationale relabeled from "deadlock" to the accurate "head-of-line blocking".

Tests

  • ✅ TestNotificationStormLogsOncePerRefreshCycle de-flaked — assertion relaxed to count < 5 with a comment explaining the poll/notification interleaving (no more exact-==1 over an interleaving-dependent quantity).
  • ✅ Added TestPromptListChangedNotificationRefreshesSnapshot.

Supply chain (govulncheck)

  • ✅ Fixed the right way: bumped toolhive v0.28.3 → v0.31.0 (pulls a patched docker/docker) and emptied the allowlist entirely — clearing all five docker advisories (the 3 new + the 2 previously accepted-as-risk). No accepted-risk debt remains; CI gate comment updated with a dated note.

CI: green except Test (race) still running at review time. Merge should wait for it.

Verdict: LGTM. Substantively approved; merging once Test (race) is green.

@JAORMX
JAORMX merged commit 2be3c05 into main Jun 26, 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.

1 participant