Skip to content

bug: bufio.Reader is not thread-safe #528

@normalnormie

Description

@normalnormie

Problem Description

When using the github.com/mark3labs/mcp-go library for stdio-based MCP servers, a race condition occurs after exactly 2-4 concurrent tool calls, causing:

  • Error reading input: read /dev/stdin: bad file descriptor
  • write |1: broken pipe errors
  • Complete server failure requiring restart
  • 0% success rate for subsequent tool calls

Root Cause Analysis

The MCP-Go library has a hardcoded race condition in /server/stdio.go:

// Problematic code in MCP-Go library
if baseMessage.Method == "tools/call" {
    go func() {  // ❌ RACE CONDITION: Multiple goroutines compete for same stdin
        response := s.server.HandleMessage(ctx, rawMessage)
        if response != nil {
            s.writeResponse(response, stdout)
        }
    }()
}

The Issue:

  • Multiple goroutines created for concurrent tool calls
  • All goroutines access the same bufio.Reader on stdin
  • bufio.Reader is NOT thread-safe
  • Concurrent access corrupts the file descriptor
  • Results in permanent stdin corruption

After trying many workarounds for hours, Claude said:

The only reliable fix is to completely replace the MCP-Go stdio server with a custom synchronous implementation that eliminates all goroutines.

The fix worked but I would like to use the mcp-go stdio

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions