mcp: handle bad trailing stdio input graciously (#179) (#192)

You can make MCP server log error, send response and then abruptly exit, with a json input malformed at the end.

While using json.RawMessage, once a valid first json is decoded, trailing bad input is silently ignored.
Without graciously handling this input, mcp server is currently sending response as well as encountering error.
It should just report error without further processing of request.

Fixes #179.
This commit is contained in:
Rishabh Nrupnarayan 2025-08-06 21:10:39 +05:30 • committed by GitHub
commit bb9087d252
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -7,6 +7,7 @@ package mcp
import (
"context"
"io"
"strings"
"testing"
"github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
@ -51,3 +52,41 @@ func TestBatchFraming(t *testing.T) {
}
}
}
func TestIOConnRead(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{
name: "valid json input",
input: `{"jsonrpc":"2.0","id":1,"method":"test","params":{}}`,
want: "",
},
{
name: "newline at the end of first valid json input",
input: `{"jsonrpc":"2.0","id":1,"method":"test","params":{}}
`,
want: "",
},
{
name: "bad data at the end of first valid json input",
input: `{"jsonrpc":"2.0","id":1,"method":"test","params":{}},`,
want: "invalid trailing data at the end of stream",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tr := newIOConn(rwc{
rc: io.NopCloser(strings.NewReader(tt.input)),
})
_, err := tr.Read(context.Background())
if err != nil && err.Error() != tt.want {
t.Errorf("ioConn.Read() = %v, want %v", err.Error(), tt.want)
}
})
}
}