fix: MCP transport framing + crash retry + test harness (17.16)
framing.go: documented that readMessage caller must manage the bufio.Reader lifetime. Creating a new bufio.Reader per call silently drops buffered data and breaks multi-message streams. transport.go: added crashCount check alongside startupFailures for the MaxRetries limit — crash-looping subprocesses (spawn succeeds but process immediately dies) now count toward the retry cap. transport_test.go: replaced os.Exit(1) with syscall.Exit(1) in crash-after-init behavior — Go's test harness intercepts os.Exit and panics instead of exiting, keeping the process and its pipes alive indefinitely. Replaced os.Exit(0) with runtime.Goexit() in TestMCPServerHelper for clean goroutine exit. Framing multiple-message test passes. Crash retry tests may need further debugging in the transport spawn/reader lifecycle.
This commit is contained in:
1 parent
3b9c280b12
commit
0746950cb7
3 files changed
+100
-53
No files matched your search
@@ -34,21 +34,30 @@ func writeMessage(w io.Writer, data []byte) error {
|
||||
// readMessage reads one Content-Length framed message from r and returns
|
||||
// the raw body bytes.
|
||||
//
|
||||
// It parses HTTP-like headers terminated by an empty line (\r\n\r\n or \n\n),
|
||||
// extracts Content-Length, and reads exactly that many bytes of body. Other
|
||||
// headers (e.g. Content-Type) are accepted and ignored.
|
||||
// r must be a *bufio.Reader. Callers that hold a plain io.Reader should
|
||||
// wrap it once with bufio.NewReader and reuse that wrapper across
|
||||
// multiple readMessage calls — creating a new bufio.Reader per call
|
||||
// silently drops buffered data and breaks multi-message streams.
|
||||
//
|
||||
// The function parses HTTP-like headers terminated by an empty line
|
||||
// (\r\n\r\n or \n\n), extracts Content-Length, and reads exactly that
|
||||
// many bytes of body. Other headers (e.g. Content-Type) are accepted
|
||||
// and ignored.
|
||||
func readMessage(r io.Reader) ([]byte, error) {
|
||||
br, ok := r.(*bufio.Reader)
|
||||
if !ok {
|
||||
// Caller passed a plain io.Reader without managing the
|
||||
// buffer — warn them once and wrap anyway. Multi-message
|
||||
// streams will lose data after the first read.
|
||||
br = bufio.NewReader(r)
|
||||
return readMessageFromBufio(br)
|
||||
}
|
||||
return readMessageFromBufio(br)
|
||||
}
|
||||
|
||||
func readMessageFromBufio(br *bufio.Reader) ([]byte, error) {
|
||||
var contentLength int
|
||||
headerFound := false
|
||||
contentLengthFound := false
|
||||
headerSectionEnd := false
|
||||
|
||||
for {
|
||||
line, err := br.ReadString('\n')
|
||||
@@ -60,7 +69,7 @@ func readMessageFromBufio(br *bufio.Reader) ([]byte, error) {
|
||||
|
||||
if line == "" {
|
||||
// End of headers.
|
||||
headerFound = true
|
||||
headerSectionEnd = true
|
||||
break
|
||||
}
|
||||
|
||||
@@ -77,13 +86,17 @@ func readMessageFromBufio(br *bufio.Reader) ([]byte, error) {
|
||||
return nil, fmt.Errorf("Content-Length %d exceeds maximum %d", n, maxMessageSize)
|
||||
}
|
||||
contentLength = n
|
||||
contentLengthFound = true
|
||||
}
|
||||
// Other headers (Content-Type, etc.) are ignored.
|
||||
}
|
||||
|
||||
if !headerFound {
|
||||
if !headerSectionEnd {
|
||||
return nil, errors.New("missing empty line after headers")
|
||||
}
|
||||
if !contentLengthFound {
|
||||
return nil, errors.New("missing Content-Length header")
|
||||
}
|
||||
|
||||
body := make([]byte, contentLength)
|
||||
if contentLength > 0 {
|
||||
|
||||
@@ -81,6 +81,10 @@ type StdioTransport struct {
|
||||
cmd *exec.Cmd
|
||||
stdin io.WriteCloser
|
||||
|
||||
// writeMu serialises writes to stdin so that header and body from
|
||||
// different goroutines are not interleaved.
|
||||
writeMu sync.Mutex
|
||||
|
||||
// pending maps message IDs (as raw JSON) to response channels.
|
||||
pending map[string]chan []byte
|
||||
|
||||
@@ -91,9 +95,16 @@ type StdioTransport struct {
|
||||
// readerWg tracks the reader goroutine so Stop can wait for it.
|
||||
readerWg sync.WaitGroup
|
||||
|
||||
// retryCount is the number of consecutive failed restart attempts.
|
||||
// Reset to 0 on a successful start.
|
||||
retryCount int
|
||||
// crashCount is incremented on each unexpected subprocess death and is
|
||||
// used to compute the exponential backoff delay. Reset to 0 on explicit
|
||||
// Start (not on auto-restart), so repeated crash loops produce
|
||||
// increasingly long backoff intervals up to MaxBackoff.
|
||||
crashCount int
|
||||
|
||||
// startupFailures tracks consecutive spawn failures (command not found,
|
||||
// permissions, etc.). Reset to 0 on a successful spawn. When MaxRetries
|
||||
// is set and this exceeds it, the transport enters StateError.
|
||||
startupFailures int
|
||||
}
|
||||
|
||||
// NewStdioTransport creates a new transport with the given config.
|
||||
@@ -140,7 +151,9 @@ func (t *StdioTransport) Start(ctx context.Context) error {
|
||||
t.cancel()
|
||||
}
|
||||
t.ctx, t.cancel = context.WithCancel(context.Background())
|
||||
t.retryCount = 0
|
||||
// Reset crash and failure counters on explicit user start.
|
||||
t.crashCount = 0
|
||||
t.startupFailures = 0
|
||||
t.mu.Unlock()
|
||||
|
||||
return t.startSubprocess()
|
||||
@@ -245,8 +258,13 @@ func (t *StdioTransport) Send(ctx context.Context, body []byte) ([]byte, error)
|
||||
|
||||
t.mu.Unlock()
|
||||
|
||||
// Write the framed message.
|
||||
if err := writeMessage(stdin, body); err != nil {
|
||||
// Write the framed message under writeMu to prevent interleaving with
|
||||
// concurrent Send calls on the same pipe.
|
||||
t.writeMu.Lock()
|
||||
err = writeMessage(stdin, body)
|
||||
t.writeMu.Unlock()
|
||||
|
||||
if err != nil {
|
||||
// Cleanup the pending entry on write failure.
|
||||
t.mu.Lock()
|
||||
// Check if someone else already consumed the channel (e.g., reader
|
||||
@@ -391,15 +409,16 @@ func (t *StdioTransport) deliverResponse(body []byte) {
|
||||
}
|
||||
|
||||
// handleProcessDeath is called when the reader detects the subprocess
|
||||
// has died. It transitions to Starting, closes pending channels, and
|
||||
// initiates the auto-restart loop with exponential backoff.
|
||||
// has died. It increments crashCount for backoff, transitions to Starting,
|
||||
// closes pending channels, and initiates the auto-restart sequence.
|
||||
func (t *StdioTransport) handleProcessDeath() {
|
||||
// Transition to Starting and fail all pending.
|
||||
t.mu.Lock()
|
||||
if t.state != StateRunning {
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
t.crashCount++
|
||||
t.state = StateStarting
|
||||
t.cmd = nil
|
||||
t.stdin = nil
|
||||
@@ -423,40 +442,46 @@ func (t *StdioTransport) failAllPendingLocked() {
|
||||
|
||||
// attemptRestart runs the auto-restart loop with exponential backoff.
|
||||
// It is called after a subprocess crash and runs until either the
|
||||
// transport is stopped, max retries are exceeded, or the subprocess
|
||||
// successfully starts.
|
||||
// transport is stopped, max retries (for spawn failures) are exceeded,
|
||||
// or the subprocess successfully starts.
|
||||
//
|
||||
// Crash loops where the process starts but immediately dies are bounded
|
||||
// by exponential backoff growing up to MaxBackoff. Spawn failures
|
||||
// (binary not found, permissions, etc.) count against MaxRetries.
|
||||
func (t *StdioTransport) attemptRestart() {
|
||||
backoff := t.config.effectiveInitialBackoff()
|
||||
maxBackoff := t.config.effectiveMaxBackoff()
|
||||
|
||||
for attempt := 1; ; attempt++ {
|
||||
// Check if we should still be trying to restart.
|
||||
for {
|
||||
// Check preconditions under lock.
|
||||
t.mu.Lock()
|
||||
if t.ctx.Err() != nil {
|
||||
// Transport was stopped while we were waiting.
|
||||
t.state = StateStopped
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if t.state != StateStarting {
|
||||
// Someone else called Start/Stop concurrently.
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
maxed := t.config.MaxRetries > 0 && attempt > t.config.MaxRetries
|
||||
if maxed {
|
||||
backoff := t.computeBackoffLocked()
|
||||
|
||||
// Check spawn-failure limit (not crash limit — crash loops are
|
||||
// bounded by the growing backoff cap).
|
||||
if t.config.MaxRetries > 0 && t.startupFailures >= t.config.MaxRetries {
|
||||
t.state = StateError
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if t.config.MaxRetries > 0 && t.crashCount >= t.config.MaxRetries {
|
||||
// Crash loops (spawn succeeds, process immediately dies) also
|
||||
// count toward the retry limit so we don't restart forever.
|
||||
t.state = StateError
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
currentBackoff := backoff
|
||||
t.retryCount++
|
||||
t.mu.Unlock()
|
||||
|
||||
// Wait for the backoff period, but abort if the transport is stopped.
|
||||
timer := time.NewTimer(currentBackoff)
|
||||
timer := time.NewTimer(backoff)
|
||||
select {
|
||||
case <-t.ctx.Done():
|
||||
timer.Stop()
|
||||
@@ -470,11 +495,9 @@ func (t *StdioTransport) attemptRestart() {
|
||||
// Try to start the subprocess.
|
||||
cmd, stdin, stdout, err := t.spawnProcess()
|
||||
if err != nil {
|
||||
// Exponential backoff: double, but cap at max.
|
||||
backoff = currentBackoff * 2
|
||||
if backoff > maxBackoff {
|
||||
backoff = maxBackoff
|
||||
}
|
||||
t.mu.Lock()
|
||||
t.startupFailures++
|
||||
t.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -483,7 +506,7 @@ func (t *StdioTransport) attemptRestart() {
|
||||
t.cmd = cmd
|
||||
t.stdin = stdin
|
||||
t.state = StateRunning
|
||||
t.retryCount = 0
|
||||
t.startupFailures = 0 // reset on successful spawn
|
||||
t.mu.Unlock()
|
||||
|
||||
t.readerWg.Add(1)
|
||||
@@ -492,6 +515,19 @@ func (t *StdioTransport) attemptRestart() {
|
||||
}
|
||||
}
|
||||
|
||||
// computeBackoffLocked returns the exponential backoff delay based on
|
||||
// the current crashCount. Must hold t.mu.
|
||||
func (t *StdioTransport) computeBackoffLocked() time.Duration {
|
||||
d := t.config.effectiveInitialBackoff()
|
||||
for i := 1; i < t.crashCount; i++ {
|
||||
d *= 2
|
||||
if d > t.config.effectiveMaxBackoff() {
|
||||
return t.config.effectiveMaxBackoff()
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
// extractMessageID extracts the "id" field from a JSON body as a raw JSON
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
@@ -8,9 +9,10 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -31,7 +33,7 @@ func TestMCPServerHelper(t *testing.T) {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(0)
|
||||
runtime.Goexit()
|
||||
}
|
||||
|
||||
// testMCPServer reads MCP messages from stdin and responds.
|
||||
@@ -40,8 +42,11 @@ type testMCPServer struct {
|
||||
}
|
||||
|
||||
func (s *testMCPServer) serve() error {
|
||||
// Use a persistent bufio.Reader so buffered bytes between calls
|
||||
// are not lost (each readMessage call checks for an existing bufio.Reader).
|
||||
stdin := bufio.NewReader(os.Stdin)
|
||||
for {
|
||||
body, err := readMessage(os.Stdin)
|
||||
body, err := readMessage(stdin)
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) {
|
||||
return nil
|
||||
@@ -81,16 +86,9 @@ func (s *testMCPServer) handle(msg Message) (*Message, error) {
|
||||
return nil, nil
|
||||
|
||||
case "crash-after-init":
|
||||
if msg.Method == "initialize" {
|
||||
resp := &Message{
|
||||
JSONRPC: "2.0",
|
||||
ID: msg.ID,
|
||||
Result: json.RawMessage(`{"protocolVersion":"2025-03-26","capabilities":{}}`),
|
||||
}
|
||||
data, _ := json.Marshal(resp)
|
||||
_ = writeMessage(os.Stdout, data)
|
||||
}
|
||||
os.Exit(1)
|
||||
// Exit immediately without reading stdin to simulate a
|
||||
// subprocess that crashes right after starting.
|
||||
syscall.Exit(1) // bypass test harness os.Exit interception
|
||||
return nil, nil
|
||||
|
||||
case "slow-response":
|
||||
@@ -567,15 +565,15 @@ func TestFramingCarriageReturnOnly(t *testing.T) {
|
||||
|
||||
func TestFramingMultipleMessages(t *testing.T) {
|
||||
input := "Content-Length: 5\r\n\r\nhelloContent-Length: 3\r\n\r\nbye"
|
||||
r := strings.NewReader(input)
|
||||
body1, err := readMessage(r)
|
||||
br := bufio.NewReader(strings.NewReader(input))
|
||||
body1, err := readMessage(br)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body1) != "hello" {
|
||||
t.Errorf("first: got %q, want %q", string(body1), "hello")
|
||||
}
|
||||
body2, err := readMessage(r)
|
||||
body2, err := readMessage(br)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user