Skip to content

feat(mcp): per-server SSE opt-out + automatic GET-hostile detection - #417

Open
jhrozek wants to merge 6 commits into
mainfrom
395-standalone-get
Open

jhrozek wants to merge 6 commits into
mainfrom
395-standalone-get

Conversation

@jhrozek

@jhrozek jhrozek commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Adds a per-server opt-out (MCP_<NAME>_DISABLE_NOTIFICATIONS=true) of the standalone SSE notification stream for gateways that accept the GET and immediately close it while POST stays healthy (ADR 0083, issue MCP: tolerate/opt out of standalone GET/SSE notification stream on hostile gateways #395).
  • Adds automatic detection of a GET-hostile gateway at runtime (ADR 0100): a RoundTripper-level observer trips after 3 consecutive hostile standalone-GET outcomes — either a completed-but-empty response or a transport-level failure (connection refused/reset/EOF) — and the next reconnect suppresses the stream without any operator action. The manual flag stays as the zero-detection-window override.
  • Trims the user-docs section to operator-level detail (symptom + self-heal behavior + manual override), moving SDK-internals detail into the ADRs.
  • Fixes a gap caught in review: the transport-failure shape wasn't being observed at all, so a hard-resetting gateway would never trip detection.
  • Fixes docs/adr/README.md, which had never indexed ADR 0083.

Test plan

  • task lint clean (root + engine + provider modules)
  • go test ./internal/adapter/mcp/... green, including new characterization tests for both GET-hostile shapes (soft-close and pre-header transport failure) and unit tests for the tracker's trip/reset/streak-composition behavior
  • docs/lint (ADR citation checker) green
  • matlatl check . --strict — 0 broken links/anchors/unreachable
  • task test's two pre-existing failures (agentimport, osfs) confirmed unrelated (same failures on origin/main without this branch's changes — host-path quirks on this machine)

🤖 Generated with Claude Code

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Panel review — Comment (three concerns inline, none a hard ship-blocker, all worth addressing or explicitly deferring).

Well-designed feature: the per-server MCP_<NAME>_DISABLE_NOTIFICATIONS opt-out (ADR 0083) follows the established MCP_<NAME>_TOKEN env pattern, the RoundTripper observer is correctly layered, the body-wrapping approach is sound, and the auto-detection heuristic (3 consecutive hostile standalone-GET outcomes with progress-reset, ADR 0100) is conservative in the common case. Test coverage is thorough at both the tracker unit level and end-to-end. Log hygiene is clean (only server name + streak count).

Three concerns flagged inline: (1) a TOCTOU race in recordOutcome — the trip CAS fires after the mutex is released, so a concurrent progress reset can flip the verdict on a stale streak; (2) the auto-detector only observes 200+text/event-stream responses and transport failures, so a non-200 standalone GET (403/500) leaves the kill→reconnect→kill cycle unobserved; (3) once the sticky auto-detection trips, the env var can't override it — only a restart re-enables the stream, which may surprise an operator who hit a transient false positive. The first is a small correctness fix; the other two are judgment calls worth an explicit decision (document the gap / decide on an override) even if the answer is "by design."

Comment thread internal/adapter/mcp/ssehealth.go Outdated
if !tripped {
return
}
if !t.hostile.CompareAndSwap(false, true) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

TOCTOU race: this hostile.CompareAndSwap(false, true) runs after t.mu.Unlock() (a few lines up). If a progress observation (hostile=false, resetting consecutiveEarlyCloses = 0) lands between the tripped read and this CAS, the CAS still succeeds (hostile is still false) and the verdict flips despite the streak having been legitimately reset. Unlikely with the SDK's serial SSE loop, but a transport-failure observeFailure firing during a body-close observe could hit it. Fix: hold t.mu across the swap, or use atomic.Bool.Swap under the lock and check the old value.

if !isStandaloneGET || resp == nil {
return resp, err
}
if resp.StatusCode != http.StatusOK ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Auto-detection gap: standalone GET responses with a non-200 status (403/500) or a non-text/event-stream content type return here without any observation. A gateway that rejects the GET with 403 yields a valid http.Response (err==nil), so neither observeFailure nor observe fires — the SDK retries → exhausts → fails the connection → the ADR 0056 reconnect reopens the GET → the cycle repeats indefinitely with no auto-detection. Rarer than "200 then close empty", but real. Consider observing non-200 standalone GETs as hostile, or document the gap in the ADR.

// next dial (this call runs on both the initial Connect and every
// reconnect, so a verdict reached mid-connection takes effect on the
// very next dial that already happens on a drop).
DisableStandaloneSSE: s.cfg.DisableNotifications || s.sseHealth.Hostile(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The auto-detection verdict is sticky and can't be overridden at runtime: DisableStandaloneSSE: s.cfg.DisableNotifications || s.sseHealth.Hostile() means MCP_<NAME>_DISABLE_NOTIFICATIONS=false can't clear a stuck hostile flag (false || true == true). An operator who hit a false positive (e.g. 3 transient network blips at startup) must restart the process — there's no un-trip signal. Consider letting an explicit cfg.DisableNotifications=false override the auto-detection (manual operator override), or document the restart requirement prominently in user-facing docs + the WARN message.

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Panel review — Request changes

Blocker: this branch adds ADRs 0226 and 0227, but current main already uses those numbers for unrelated decisions. Rebasing will produce path/content conflicts and duplicate ADR index entries. Please renumber these new ADRs to unused higher numbers and update all references, including docs/adr/README.md and user docs.

Important: add a monitor-seam test proving a request-context cancellation does not advance the hostile streak or emit the auto-disable warning (internal/adapter/mcp/ssehealth.go:133-141). A cancellation during shutdown or timeout must not disable notifications.

Advisory: use exact media-type parsing (mime.ParseMediaType) rather than substring matching for Content-Type; application/json; note=text/event-stream is not an SSE response. Consider direct coverage for the observing-body byte/progress and idempotent-close behavior too.

The previous review concerns are addressed: tracker state is synchronized, completed invalid responses are observed, and process-lifetime stickiness is now an explicit documented decision.

jhrozek and others added 5 commits September 11, 2026 11:33
Some authenticated Streamable HTTP gateways close or reject the optional
standalone GET/SSE notification stream after initialization while POST
stays healthy. The go-sdk's handleSSE retries the dropped GET, then fails
the WHOLE connection (c.fail() poisons the POST channel too), so ADR 0056's
reconnect heals it as a fresh initialize — a new Mcp-Session-Id (server-side
session state lost) — and against a still-hostile gateway the
kill -> reconnect -> kill cycle repeats, charging one unlucky tool call the
dial timeout per cycle.

Add ServerConfig.DisableNotifications mapping to the transport's
DisableStandaloneSSE in dial (the single construction site, so reconnects
honor it too), surfaced as MCP_<NAME>_DISABLE_NOTIFICATIONS=true on the
shared --mcp-server flag — the same name-derived env convention as
MCP_<NAME>_TOKEN, so all three mains inherit it with no new flag. An
unparseable value fails parse loudly. Default stays on (ADR 0057); the
opt-out trades that server's list-changed notifications for a stable
POST-only session. ToolHive-discovery / ACP / agent-def-inline construction
sites get no knob deliberately (ADR 0083): ToolHive proxies terminate the
GET correctly and the other surfaces have no per-server env channel.

Tests: a characterization test locks in the ADR 0056 mitigation (GET
hostile + POST healthy -> exactly one transparent reconnect pair -> call
succeeds, and the churn re-opens the GET), and the fix test asserts the
opt-out sends zero GETs, succeeds first-try, and logs no reconnect.
cliconfig gains the env-parse matrix (per-server true / explicit false /
fail-loud typo / unset default).

ADR 0083 amends ADR 0057 (frozen — pointer lives on the new ADR's Amends
header, not an edit to 0057); ADR 0027 List 1 row 28 marked only-when-
enabled; architecture/tracker/user-docs updated in the same change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ADR 0083 added a manual per-server opt-out (MCP_<NAME>_DISABLE_NOTIFICATIONS)
for gateways that accept the standalone SSE GET and immediately close it
while POST stays healthy, but it only helps an operator who already knows
their gateway behaves this way — the first encounter still pays the full
kill -> reconnect -> kill churn before anyone can discover the flag.

Add sseHealthTracker (internal/adapter/mcp/ssehealth.go): a RoundTripper-level
observer, installed on every server's transport, that counts consecutive
standalone-GET responses delivering zero bytes within 5s. After 3 in a row —
well inside the go-sdk's own retry budget, so no SDK behavior is touched —
it flips a sticky per-server verdict that Server.dial ORs into
DisableStandaloneSSE alongside the existing manual flag. The very next dial
(which a drop already triggers via ADR 0056's reconnect) picks it up, so no
new reconnect path or goroutine is needed. One WARN logs on the false->true
transition; the manual flag stays as the zero-detection-window override.

Updates TestGetHostileGatewayReconnectsTransparently's tail: the churn no
longer repeats after auto-detect trips (the "honest residual cost" the old
assertion characterized is exactly what this change removes) and adds
ssehealth_test.go for the trip/reset-on-progress contract in isolation.

ADR 0100 amends ADR 0083. Also fixes docs/adr/README.md, which had never
indexed ADR 0083 itself (caught by matlatl check --strict while adding 0100's
entry).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The section (added in #395, expanded for ADR 0100's auto-detection) carried
SDK-internal mechanics (Mcp-Session-Id, the go-sdk's retry/backoff behavior,
the kill-reconnect-kill cycle) that belong in the ADRs, not user-docs. Cut it
to symptom + self-heal behavior + the manual override, matching the density
of the rest of this doc.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…es too

sseMonitorRoundTripper.RoundTrip only recorded a completed response (the
"200, then closed empty" gateway shape); a transport-level failure —
connection refused, TCP reset, EOF before any response ever arrives —
returned immediately without reporting to the tracker. The pinned SDK
retries that failure the same way it retries a hostile-but-completed GET,
and eventually poisons the session the same way, but since the tracker never
saw these attempts, Hostile() stayed false forever and every reconnect
reopened the doomed GET indefinitely against a gateway that hard-resets
instead of soft-closing.

Split the trip/streak logic into a shared recordOutcome, add observeFailure
for the transport-failure path (unconditionally hostile — a request that
never completed carries no "maybe it's just a slow legitimate stream"
ambiguity — excluding the caller's own context cancellation), and call it
from RoundTrip's error branch.

Add newPreHeaderCloseServer (hijack-and-close before any response) as a
characterization test for this shape, plus direct unit coverage that the two
failure shapes share one streak. Update ADR 0100 to describe both observation
paths.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Rebasing onto main picked up the user-docs restructure (files moved under
user-docs/building/); the two new MCP standalone-SSE ADRs still cited the
pre-move path, which TestRealDesignDocsCitations now flags as dead.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…bility row

sseHealthTracker guards a plain bool verdict with sync.Mutex, not an
atomic.Bool as the row claimed.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

This branch has not been deployed

No deployments
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.

2 participants