From bfa1c8e19201fc8303b714136d98a03f2bfd65b1 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:51:37 -0600 Subject: [PATCH 1/3] fix(mcpx): close mcpclient data races: era mirrors + Detach/recvLoop exclusion (#2842) --- pkgs/mcpx/internal/mcpclient/client.go | 22 +++++++++++++--------- pkgs/mcpx/internal/mcpclient/handoff.go | 14 ++++++++++---- pkgs/mcpx/internal/mcpclient/modern.go | 8 ++++++-- pkgs/mcpx/internal/mcpclient/request.go | 2 +- pkgs/mcpx/internal/mcpclient/stdio.go | 14 ++++++++++---- 5 files changed, 40 insertions(+), 20 deletions(-) diff --git a/pkgs/mcpx/internal/mcpclient/client.go b/pkgs/mcpx/internal/mcpclient/client.go index 488c882d6c..a045c9285a 100644 --- a/pkgs/mcpx/internal/mcpclient/client.go +++ b/pkgs/mcpx/internal/mcpclient/client.go @@ -508,6 +508,10 @@ func (c *Client) finishLegacy(ctx context.Context, ir initResult) error { c.Negotiated = ir.ProtocolVersion c.negotiated.Store(ir.ProtocolVersion) c.Era = EraLegacy + // Publish the era mirror, as probe and Resume do: a connection that + // settled modern and then fell back to a legacy recovery would + // otherwise leave the mirror saying modern for its whole life. + c.modern.Store(false) if h, ok := c.t.(interface{ setNegotiated(string) }); ok { h.setNegotiated(ir.ProtocolVersion) @@ -952,7 +956,7 @@ func declares(caps map[string]json.RawMessage, capability, flag string) bool { // subscriptions/listen, so against a modern server this adds the URI to the // connection's listen stream, which is reopened with the new filter. func (c *Client) SubscribeResource(ctx context.Context, uri string) error { - if c.Era == EraModern { + if c.modernEra() == EraModern { c.mu.Lock() l := c.listen c.mu.Unlock() @@ -968,7 +972,7 @@ func (c *Client) SubscribeResource(ctx context.Context, uri string) error { // UnsubscribeResource stops notifications for a resource. func (c *Client) UnsubscribeResource(ctx context.Context, uri string) error { - if c.Era == EraModern { + if c.modernEra() == EraModern { c.mu.Lock() l := c.listen c.mu.Unlock() @@ -1022,7 +1026,7 @@ func (c *Client) ListResourceTemplatesWithHints(ctx context.Context) ([]Resource // a modern server this only records the level, and every later request // carries it. func (c *Client) SetLogLevel(ctx context.Context, level string) error { - if c.Era == EraModern { + if c.modernEra() == EraModern { c.mu.Lock() c.logLevel = level c.mu.Unlock() @@ -1213,7 +1217,7 @@ func (c *Client) roundTrip(ctx context.Context, method string, params json.RawMe } return c.roundTripOnce(ctx, method, params) } - if attempt > 0 || !allowReissue || c.Era != EraModern || ctx.Err() != nil || !isStreamLost(err) { + if attempt > 0 || !allowReissue || c.modernEra() != EraModern || ctx.Err() != nil || !isStreamLost(err) { return raw, err } } @@ -1327,7 +1331,7 @@ func (c *Client) roundTripOnce(ctx context.Context, method string, params json.R // server/discover instead, which every modern server MUST implement and // which, like ping, does nothing but answer. func (c *Client) Ping(ctx context.Context) error { - if c.Era == EraModern { + if c.modernEra() == EraModern { return c.call(ctx, "server/discover", json.RawMessage(`{}`), nil) } return c.call(ctx, "ping", json.RawMessage(`{}`), nil) @@ -1348,7 +1352,7 @@ func (c *Client) nextPage(next *string, sent *string) (string, bool) { if next == nil { return "", false } - if *next == "" && c.Era != EraModern { + if *next == "" && c.modernEra() != EraModern { return "", false } if sent != nil && *sent == *next { @@ -1649,7 +1653,7 @@ func (c *Client) CallTool(ctx context.Context, name string, args any) (json.RawM // modern is server-directed, so the plain call below runs and a // task answer is polled to its terminal result before returning. support := c.resolveTaskSupport(name) - if support == taskSupportRequired && c.Era == EraLegacy { + if support == taskSupportRequired && c.modernEra() == EraLegacy { raw, err := c.callToolAsLegacyTask(ctx, name, args) if err != nil { // A -32042 can surface from the task-augmented call itself @@ -1711,7 +1715,7 @@ func (c *Client) CallTool(ctx context.Context, name string, args any) (json.RawM // only a required tool's: advertising the tasks extension lets // the server answer an optional tool with a task past its eager // window, and the handle is not the tool's result. - if c.Era == EraModern && isTaskResult(raw) { + if c.modernEra() == EraModern && isTaskResult(raw) { raw, err = c.finishModernTask(ctx, name, raw) if err != nil { return nil, err @@ -1733,7 +1737,7 @@ func (c *Client) ReadResource(ctx context.Context, uri string) (json.RawMessage, var raw json.RawMessage if err := c.call(ctx, "resources/read", params, &raw); err != nil { var re *rpcError - if errors.As(err, &re) && (re.Code == codeResourceNotFound || (re.Code == codeInvalidParams && c.Era == EraModern)) { + if errors.As(err, &re) && (re.Code == codeResourceNotFound || (re.Code == codeInvalidParams && c.modernEra() == EraModern)) { return nil, &ResourceNotFoundError{URI: uri, err: re} } return nil, err diff --git a/pkgs/mcpx/internal/mcpclient/handoff.go b/pkgs/mcpx/internal/mcpclient/handoff.go index cb0068694b..60f1c9eb01 100644 --- a/pkgs/mcpx/internal/mcpclient/handoff.go +++ b/pkgs/mcpx/internal/mcpclient/handoff.go @@ -69,17 +69,23 @@ func (t *StdioTransport) Detach() (*StdioHandoff, error) { return nil, fmt.Errorf("child %d: %w", t.pid, err) } t.writeMu.Lock() - if t.closed.Load() || t.detached { + if t.closed.Load() || t.detached.Load() { t.writeMu.Unlock() return nil, errors.New("stdio transport is not attached") } - t.detached = true + t.detached.Store(true) t.writeMu.Unlock() _ = t.outR.SetReadDeadline(aLongTimeAgo) _ = t.errR.SetReadDeadline(aLongTimeAgo) + // Hold readMu across the snapshot, not just as a wait for a read in + // progress: a read loop whose Recv just returned can start the next + // one and write pending while Detach reads it below -- the + // readLine/Detach data race in #2842. A loop still waiting on + // readMu when Detach returns meets the detached check in Recv + // instead of consuming the successor's frames. t.readMu.Lock() - t.readMu.Unlock() + defer t.readMu.Unlock() <-t.stderrDone buffered, _ := t.stdout.Peek(t.stdout.Buffered()) @@ -98,7 +104,7 @@ func (t *StdioTransport) Detach() (*StdioHandoff, error) { // Reattach resumes reading after a Detach that was not handed on. func (t *StdioTransport) Reattach() { t.writeMu.Lock() - t.detached = false + t.detached.Store(false) t.writeMu.Unlock() _ = t.outR.SetReadDeadline(time.Time{}) _ = t.errR.SetReadDeadline(time.Time{}) diff --git a/pkgs/mcpx/internal/mcpclient/modern.go b/pkgs/mcpx/internal/mcpclient/modern.go index cfaa72c7da..2796a298fc 100644 --- a/pkgs/mcpx/internal/mcpclient/modern.go +++ b/pkgs/mcpx/internal/mcpclient/modern.go @@ -148,7 +148,7 @@ func (c *Client) elicitModeDeclared(mode string) bool { case "", "form": return true case "url": - return h != nil && (c.Era == EraModern || spec.AtOrAfter("2025-11-25")(c.Negotiated)) + return h != nil && (c.modernEra() == EraModern || spec.AtOrAfter("2025-11-25")(c.negotiatedVersion())) } return false } @@ -614,9 +614,13 @@ func (c *Client) cancelled(method string, id int64, cause error) { // mirrorsHeaders reports whether this connection must mirror x-mcp-header // parameters: modern, over HTTP. stdio clients MAY ignore the annotations, // and a legacy revision never defined them. +// +// The atomic modern mirror, not c.Era: CallTool reaches this on the +// caller's goroutine while a concurrent call's recovery (finishLegacy) +// may be writing Era. That pair is the data race #2842 reproduced. func (c *Client) mirrorsHeaders() bool { _, isHTTP := c.t.(*HTTPTransport) - return isHTTP && c.Era == EraModern + return isHTTP && c.modern.Load() } // Warning is something mcpx noticed about a server that is not an error. diff --git a/pkgs/mcpx/internal/mcpclient/request.go b/pkgs/mcpx/internal/mcpclient/request.go index a399e78983..aba5dd4c46 100644 --- a/pkgs/mcpx/internal/mcpclient/request.go +++ b/pkgs/mcpx/internal/mcpclient/request.go @@ -51,7 +51,7 @@ func (c *Client) Complete(ctx context.Context, params json.RawMessage) (json.Raw // 2024-11-05 defined completion/complete with no capability to gate // it, so a server of that era is asked, and its method-not-found read // as the same absence a later server signals by not declaring. - legacy := c.Negotiated == "2024-11-05" + legacy := c.negotiatedVersion() == "2024-11-05" if !legacy && !c.Supports("completions") { return nil, false, nil } diff --git a/pkgs/mcpx/internal/mcpclient/stdio.go b/pkgs/mcpx/internal/mcpclient/stdio.go index 54c08623de..b9665601b0 100644 --- a/pkgs/mcpx/internal/mcpclient/stdio.go +++ b/pkgs/mcpx/internal/mcpclient/stdio.go @@ -43,9 +43,10 @@ type StdioTransport struct { // write. writeMu sync.Mutex closed atomic.Bool - // detached is set while another process owns the child's pipes; see Detach. - // Guarded by writeMu. - detached bool + // detached is set while another process owns the child's pipes; see + // Detach. An atomic, like closed: Recv reads it under readMu while + // Detach sets it without holding readMu. + detached atomic.Bool // readMu is held by Recv, so Detach can wait out a read in progress. readMu sync.Mutex // pending is the start of a frame whose end had not arrived when a read @@ -200,7 +201,7 @@ func (t *StdioTransport) startStderr() { func (t *StdioTransport) Send(ctx context.Context, msg []byte) error { t.writeMu.Lock() defer t.writeMu.Unlock() - if t.closed.Load() || t.detached { + if t.closed.Load() || t.detached.Load() { return errors.New("stdio transport closed") } frame := append(msg, '\n') @@ -241,6 +242,11 @@ func (t *StdioTransport) lastWords(n int) string { func (t *StdioTransport) Recv() ([]byte, error) { t.readMu.Lock() defer t.readMu.Unlock() + if t.detached.Load() { + // A read loop that was waiting on readMu while Detach took the + // pipes must not consume frames the successor owns (#2842). + return nil, errors.New("stdio transport is detached") + } for { line, err := t.readLine() if err != nil { From 43fc9a058c53d747e7e61e11087344c3489d1e6a Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:56:42 -0600 Subject: [PATCH 2/3] test(mcpx): Recv refuses while detached (#2842) --- pkgs/mcpx/internal/mcpclient/handoff_test.go | 29 ++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/pkgs/mcpx/internal/mcpclient/handoff_test.go b/pkgs/mcpx/internal/mcpclient/handoff_test.go index ccc025ae2b..145af9d931 100644 --- a/pkgs/mcpx/internal/mcpclient/handoff_test.go +++ b/pkgs/mcpx/internal/mcpclient/handoff_test.go @@ -140,3 +140,32 @@ func TestClientHandoffCommitsOnlyWhenActivated(t *testing.T) { _ = second.Close() <-adopted.exited } + +// TestRecvRefusesWhileDetached pins the #2842 exclusion: after Detach, a +// Recv that was waiting (or starts late) must refuse at once instead of +// consuming frames the successor owns -- and must not write pending +// against Detach's snapshot of it. +func TestRecvRefusesWhileDetached(t *testing.T) { + tr, err := NewStdio(StdioOptions{Command: "sh", Args: []string{"-c", echoScript}, InheritEnv: true}) + if err != nil { + t.Fatal(err) + } + if _, err := tr.Detach(); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := tr.Recv() + done <- err + }() + select { + case err := <-done: + if err == nil || !strings.Contains(err.Error(), "detached") { + t.Fatalf("Recv on a detached transport: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("Recv on a detached transport blocked instead of refusing") + } + tr.Reattach() + _ = tr.Close() +} From 9026fbaaa3fc56459eaf1c33fa77f4194bbf3051 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:53:54 -0600 Subject: [PATCH 3/3] test(mcpx): cover Recv queued behind Detach (#2842) --- pkgs/mcpx/internal/mcpclient/handoff_test.go | 138 ++++++++++++++++--- 1 file changed, 122 insertions(+), 16 deletions(-) diff --git a/pkgs/mcpx/internal/mcpclient/handoff_test.go b/pkgs/mcpx/internal/mcpclient/handoff_test.go index 145af9d931..31f75e549a 100644 --- a/pkgs/mcpx/internal/mcpclient/handoff_test.go +++ b/pkgs/mcpx/internal/mcpclient/handoff_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "strings" + "sync" "testing" "time" ) @@ -141,31 +142,136 @@ func TestClientHandoffCommitsOnlyWhenActivated(t *testing.T) { <-adopted.exited } -// TestRecvRefusesWhileDetached pins the #2842 exclusion: after Detach, a -// Recv that was waiting (or starts late) must refuse at once instead of -// consuming frames the successor owns -- and must not write pending -// against Detach's snapshot of it. -func TestRecvRefusesWhileDetached(t *testing.T) { - tr, err := NewStdio(StdioOptions{Command: "sh", Args: []string{"-c", echoScript}, InheritEnv: true}) +// TestRecvQueuedBehindDetachDoesNotConsumeSuccessorFrame pins the #2842 +// exclusion: a Recv queued behind Detach must refuse instead of consuming a +// frame the successor owns. +func TestRecvQueuedBehindDetachDoesNotConsumeSuccessorFrame(t *testing.T) { + const successorFrame = `{"n":"successor"}` + script := `printf '{"n":"successor"}\n'; printf 'ready\n' >&2; ` + echoScript + tr, err := NewStdio(StdioOptions{Command: "sh", Args: []string{"-c", script}, InheritEnv: true}) if err != nil { t.Fatal(err) } - if _, err := tr.Detach(); err != nil { + transferred := false + t.Cleanup(func() { + if !transferred { + _ = tr.Close() + } + }) + + // Keep Detach inside its readMu critical section so the receiver below is + // queued behind it. The real stderr drain owns its original channel; this + // replacement only provides a deterministic gate for the test. + readRelease := make(chan struct{}) + tr.stderrDone = readRelease + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(readRelease) }) } + defer release() + + readyDeadline := time.NewTimer(2 * time.Second) + defer readyDeadline.Stop() + readyPoll := time.NewTicker(time.Millisecond) + defer readyPoll.Stop() + for !strings.Contains(tr.Stderr(100), "ready") { + select { + case <-readyDeadline.C: + t.Fatal("child did not write its successor frame") + case <-readyPoll.C: + } + } + + detachDone := make(chan struct { + handoff *StdioHandoff + err error + }, 1) + go func() { + handoff, err := tr.Detach() + detachDone <- struct { + handoff *StdioHandoff + err error + }{handoff, err} + }() + + // Wait until Detach owns readMu and is held at readRelease. + deadline := time.Now().Add(2 * time.Second) + for { + if tr.readMu.TryLock() { + tr.readMu.Unlock() + if time.Now().After(deadline) { + t.Fatal("Detach did not acquire readMu") + } + time.Sleep(time.Millisecond) + continue + } + break + } + + recvStarted := make(chan struct{}) + recvDone := make(chan struct { + line []byte + err error + }, 1) + go func() { + close(recvStarted) + line, err := tr.Recv() + recvDone <- struct { + line []byte + err error + }{line, err} + }() + <-recvStarted + select { + case result := <-recvDone: + t.Fatalf("Recv escaped Detach's read lock: line=%q err=%v", result.line, result.err) + case <-time.After(20 * time.Millisecond): + } + + release() + var detached struct { + handoff *StdioHandoff + err error + } + select { + case detached = <-detachDone: + case <-time.After(2 * time.Second): + t.Fatal("Detach did not return after releasing its read lock") + } + if detached.err != nil { + t.Fatal(detached.err) + } + select { + case result := <-recvDone: + if result.err == nil || !strings.Contains(result.err.Error(), "detached") { + t.Fatalf("queued Recv consumed the successor's frame: line=%q err=%v", result.line, result.err) + } + case <-time.After(2 * time.Second): + t.Fatal("queued Recv did not return after Detach") + } + + successor, err := AdoptStdio(*detached.handoff) + if err != nil { t.Fatal(err) } - done := make(chan error, 1) + transferred = true + t.Cleanup(func() { + _ = successor.Close() + <-successor.exited + }) + type recvResult struct { + line []byte + err error + } + successorRecv := make(chan recvResult, 1) go func() { - _, err := tr.Recv() - done <- err + line, err := successor.Recv() + successorRecv <- recvResult{line, err} }() select { - case err := <-done: - if err == nil || !strings.Contains(err.Error(), "detached") { - t.Fatalf("Recv on a detached transport: %v", err) + case result := <-successorRecv: + if result.err != nil || string(result.line) != successorFrame { + t.Fatalf("successor frame after handoff: line=%q err=%v", result.line, result.err) } case <-time.After(2 * time.Second): - t.Fatal("Recv on a detached transport blocked instead of refusing") + t.Fatal("successor could not read its frame") } - tr.Reattach() - _ = tr.Close() }