Skip to content

fix: use bufio.Scanner for stdio transport to avoid panic when stdio mcp server outputs a long line #464

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions client/transport/stdio.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type Stdio struct {
cmd *exec.Cmd
cmdFunc CommandFunc
stdin io.WriteCloser
stdout *bufio.Reader
stdout *bufio.Scanner
stderr io.ReadCloser
responses map[string]chan *JSONRPCResponse
mu sync.RWMutex
Expand Down Expand Up @@ -72,7 +72,7 @@ func WithCommandLogger(logger util.Logger) StdioOption {
func NewIO(input io.Reader, output io.WriteCloser, logging io.ReadCloser) *Stdio {
return &Stdio{
stdin: output,
stdout: bufio.NewReader(input),
stdout: bufio.NewScanner(input),
stderr: logging,

responses: make(map[string]chan *JSONRPCResponse),
Expand Down Expand Up @@ -180,7 +180,7 @@ func (c *Stdio) spawnCommand(ctx context.Context) error {
c.cmd = cmd
c.stdin = stdin
c.stderr = stderr
c.stdout = bufio.NewReader(stdout)
c.stdout = bufio.NewScanner(stdout)

if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start command: %w", err)
Expand Down Expand Up @@ -247,14 +247,15 @@ func (c *Stdio) readResponses() {
case <-c.done:
return
default:
line, err := c.stdout.ReadString('\n')
if err != nil {
if err != io.EOF && !errors.Is(err, context.Canceled) {
if !c.stdout.Scan() {
err := c.stdout.Err()
if err != nil && !errors.Is(err, context.Canceled) {
c.logger.Errorf("Error reading from stdout: %v", err)
}
return
}

line := c.stdout.Text()
// First try to parse as a generic message to check for ID field
var baseMessage struct {
JSONRPC string `json:"jsonrpc"`
Expand Down