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

Conversation

WingT
Copy link

@WingT WingT commented Jul 1, 2025

Description

Fixes #462

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Tests only (no functional changes)
  • Other (please describe):

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

MCP Spec Compliance

  • This PR implements a feature defined in the MCP specification
  • Link to relevant spec section: Link text
  • Implementation follows the specification exactly

Summary by CodeRabbit

  • Refactor
    • Improved the way output is read from subprocesses for better reliability and error handling. No changes to user-facing features or workflows.

Copy link
Contributor

coderabbitai bot commented Jul 1, 2025

Walkthrough

The code replaces the use of bufio.Reader with bufio.Scanner for reading subprocess stdout in the Stdio struct and associated methods. The reading logic in readResponses is updated to use Scanner.Scan() instead of ReadString('\n'), modifying how lines are read and errors are handled in the response loop.

Changes

File(s) Change Summary
Stdio transport updates
client/transport/stdio.go
Replaced bufio.Reader with bufio.Scanner for stdout in Stdio struct and related methods. Updated readResponses to use Scanner.Scan() for line reading. Adjusted initialization in NewIO and spawnCommand accordingly.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent panic in mcp-go stdio tools when tool outputs a very long line (#462)
Avoid use of bufio.Reader for stdin/stdout to address buffer limitations (#462)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Possibly related issues

Possibly related PRs

Suggested reviewers

  • pottekkat

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 071098d and 92d6349.

📒 Files selected for processing (1)
  • client/transport/stdio.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/transport/stdio.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
client/transport/stdio.go (1)

170-181: Reading logic correctly implements Scanner pattern, but consider improving error handling.

The implementation correctly follows the Scanner pattern:

  1. Scan() returns false on EOF or error
  2. Err() distinguishes between normal EOF and actual errors
  3. Text() provides the line content without newline

This should indeed prevent the panic issue mentioned in the PR.

However, consider using a structured logger instead of fmt.Printf for error reporting, as this is a library component:

-				fmt.Printf("Error reading response: %v\n", err)
+				// Consider using a structured logger here
+				fmt.Printf("Error reading response: %v\n", err)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1eddde7 and 071098d.

📒 Files selected for processing (1)
  • client/transport/stdio.go (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:16.959Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.
Learnt from: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
🔇 Additional comments (3)
client/transport/stdio.go (3)

27-27: LGTM: Field type change is appropriate for the fix.

The change from *bufio.Reader to *bufio.Scanner aligns with the objective to prevent panics during line reading. Scanner provides more robust EOF handling compared to Reader.


42-42: LGTM: Constructor properly updated for Scanner.

The initialization correctly uses bufio.NewScanner(input) instead of bufio.NewReader(input), maintaining consistency with the field type change.


117-117: LGTM: Subprocess initialization updated correctly.

The spawnCommand method properly initializes the stdout field with bufio.NewScanner(stdout), consistent with the type change and fixing approach.

…mcp server outputs a long line

Change-Id: Iaaaf44f80d2e49f5275c5f6903c87dcb4dbb53a3
@WingT WingT changed the title fix: use bufio.Scanner for stdio transport to avoid panic fix: use bufio.Scanner for stdio transport to avoid panic when stdio mcp server outputs a long line Aug 8, 2025
@ezynda3
Copy link
Contributor

ezynda3 commented Aug 8, 2025

I was under the impression that bufio.NewScanner was limited to 64kb which is why we use NewReader instead. @coderabbitai, am I wrong about this?

Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Tip

For best results, initiate chat on the files or code changes.

@ezynda3 You’re right: bufio.Scanner defaults to a ~64 KiB max token size. It won’t panic, but Scan() will fail with ErrTooLong on longer lines unless you raise the limit via Scanner.Buffer. If we keep Scanner for stdio, we should call Buffer with a larger max (e.g., a few MiB or configurable) to handle very long lines safely. Otherwise, a streaming approach with bufio.Reader/json.Decoder can avoid a hard cap.

Would you like me to propose a small patch that sets Scanner.Buffer with a sane default and a knob to tweak it?


✏️ Learnings added
Learnt from: ezynda3
URL: https://github.com/mark3labs/mcp-go/pull/464

Timestamp: 2025-08-08T15:37:18.417Z
Learning: In mark3labs/mcp-go stdio transport, using bufio.Scanner without calling Scanner.Buffer imposes a 64 KiB per-line limit; to support very long lines safely, set a larger max via Scanner.Buffer or use a streaming Reader/json.Decoder approach.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.

Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@ezynda3 You’re right: bufio.Scanner defaults to a 64KB max token. It won’t panic, but it will return ErrTooLong for longer lines unless we raise the limit via Scanner.Buffer(initialBuf, maxToken). The current PR uses NewScanner without Buffer, so long lines >64KB will still fail (albeit gracefully).

If we stick with Scanner, I suggest setting something like:

  • initial buffer: 64KiB–256KiB
  • max token: e.g., 16–64MiB (tunable/configurable)

Alternatively, using bufio.Reader with ReadBytes('\n') and accumulating when ErrBufferFull occurs also handles arbitrarily long lines without the Scanner limit.

Would you prefer I patch this PR to call Scanner.Buffer with a sane default (e.g., 16MiB) and make it configurable?


🏁 Script executed:

#!/bin/bash
set -e
echo "Locate stdio.go:"
fd -a 'stdio.go' || true

echo "Show client/transport/stdio.go (if exists):"
if [ -f "client/transport/stdio.go" ]; then
  nl -ba client/transport/stdio.go | sed -n '1,240p'
fi

echo "Search for NewScanner and Buffer usage across repo:"
rg -n "bufio.NewScanner|Scanner.Buffer" -A2 -B2 || true

Length of output: 2203


@ezynda3 You’re not wrong. bufio.Scanner defaults to a 64 KiB max token. Our script confirms this PR uses NewScanner in client/transport/stdio.go (Line 75, Line 183) and there’s no Scanner.Buffer anywhere in the repo, so very long lines would still hit ErrTooLong.

If we keep Scanner, we should raise the limit. Minimal change:

// In NewIO(...)
scanner := bufio.NewScanner(input)
buf := make([]byte, 256*1024)           // 256 KiB initial buffer
scanner.Buffer(buf, 64*1024*1024)       // 64 MiB max token
// scanner.Split(bufio.ScanLines)       // optional; default is ScanLines
return &Stdio{
    stdin:  output,
    stdout: scanner,
    stderr: logging,
}

// In spawnCommand(...)
c.stdout = bufio.NewScanner(stdout)
buf := make([]byte, 256*1024)
c.stdout.Buffer(buf, 64*1024*1024)

Alternatively, we can revert to bufio.Reader and accumulate on ErrBufferFull to avoid any hard cap. Preference?


✏️ Learnings added
Learnt from: ezynda3
URL: https://github.com/mark3labs/mcp-go/pull/464

Timestamp: 2025-08-08T15:38:52.889Z
Learning: In mark3labs/mcp-go, for stdio line reading (e.g., client/transport/stdio.go), maintainers prefer bufio.Reader over bufio.Scanner because Scanner’s default 64 KiB token limit is problematic for long lines. If Scanner is used, its buffer limit should be raised via Scanner.Buffer.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.

@ezynda3
Copy link
Contributor

ezynda3 commented Aug 8, 2025

[!TIP]
For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@ezynda3 You’re right: bufio.Scanner defaults to a 64KB max token. It won’t panic, but it will return ErrTooLong for longer lines unless we raise the limit via Scanner.Buffer(initialBuf, maxToken). The current PR uses NewScanner without Buffer, so long lines >64KB will still fail (albeit gracefully).

If we stick with Scanner, I suggest setting something like:

  • initial buffer: 64KiB–256KiB
  • max token: e.g., 16–64MiB (tunable/configurable)

Alternatively, using bufio.Reader with ReadBytes('\n') and accumulating when ErrBufferFull occurs also handles arbitrarily long lines without the Scanner limit.

Would you prefer I patch this PR to call Scanner.Buffer with a sane default (e.g., 16MiB) and make it configurable?


🏁 Script executed:

#!/bin/bash
set -e
echo "Locate stdio.go:"
fd -a 'stdio.go' || true

echo "Show client/transport/stdio.go (if exists):"
if [ -f "client/transport/stdio.go" ]; then
  nl -ba client/transport/stdio.go | sed -n '1,240p'
fi

echo "Search for NewScanner and Buffer usage across repo:"
rg -n "bufio.NewScanner|Scanner.Buffer" -A2 -B2 || true

Length of output: 2203


@ezynda3 You’re not wrong. bufio.Scanner defaults to a 64 KiB max token. Our script confirms this PR uses NewScanner in client/transport/stdio.go (Line 75, Line 183) and there’s no Scanner.Buffer anywhere in the repo, so very long lines would still hit ErrTooLong.

If we keep Scanner, we should raise the limit. Minimal change:

// In NewIO(...)
scanner := bufio.NewScanner(input)
buf := make([]byte, 256*1024)           // 256 KiB initial buffer
scanner.Buffer(buf, 64*1024*1024)       // 64 MiB max token
// scanner.Split(bufio.ScanLines)       // optional; default is ScanLines
return &Stdio{
    stdin:  output,
    stdout: scanner,
    stderr: logging,
}

// In spawnCommand(...)
c.stdout = bufio.NewScanner(stdout)
buf := make([]byte, 256*1024)
c.stdout.Buffer(buf, 64*1024*1024)

Alternatively, we can revert to bufio.Reader and accumulate on ErrBufferFull to avoid any hard cap. Preference?


✏️ Learnings added
Learnt from: ezynda3
URL: https://github.com/mark3labs/mcp-go/pull/464

Timestamp: 2025-08-08T15:38:52.889Z
Learning: In mark3labs/mcp-go, for stdio line reading (e.g., client/transport/stdio.go), maintainers prefer bufio.Reader over bufio.Scanner because Scanner’s default 64 KiB token limit is problematic for long lines. If Scanner is used, its buffer limit should be raised via Scanner.Buffer.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.

@coderabbitai Is there any way to keep bufio.Reader and avoid panics?

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.

bug: mcp-go would panic for stdio tools if the tool outputs a really long line
2 participants