From 71532cc61f76e08bd8683c243fa9efdc0d879e91 Mon Sep 17 00:00:00 2001 From: Chao Chen <209239467+surlymochan@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:45:34 +0800 Subject: [PATCH] mcp: parse SSE field values per the SSE spec Strip at most one leading space from an event field value, instead of trimming surrounding whitespace, so that multi-line data payloads and event names, ids and retry values keep the bytes the server sent. --- mcp/event.go | 11 +++++++---- mcp/event_test.go | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/mcp/event.go b/mcp/event.go index 305b6502b..320ecdeb7 100644 --- a/mcp/event.go +++ b/mcp/event.go @@ -158,15 +158,18 @@ func scanEventsLimited(r io.Reader, maxEventSize int) iter.Seq2[Event, error] { if b, a, found := bytes.Cut(line, []byte{':'}); found { before, after = b, a } + // A field value is everything after the colon, with at most one + // leading U+0020 removed; any other whitespace is part of the value. + value := bytes.TrimPrefix(after, []byte{' '}) switch { case bytes.Equal(before, eventKey): - evt.Name = strings.TrimSpace(string(after)) + evt.Name = string(value) case bytes.Equal(before, idKey): - evt.ID = strings.TrimSpace(string(after)) + evt.ID = string(value) case bytes.Equal(before, retryKey): - evt.Retry = strings.TrimSpace(string(after)) + evt.Retry = string(value) case bytes.Equal(before, dataKey): - data := bytes.TrimSpace(after) + data := value if dataBuf == nil { dataBuf = new(bytes.Buffer) } else { diff --git a/mcp/event_test.go b/mcp/event_test.go index 7fa4a1875..096cce96e 100644 --- a/mcp/event_test.go +++ b/mcp/event_test.go @@ -134,6 +134,29 @@ func TestScanEvents(t *testing.T) { {Data: []byte("hello\n")}, }, }, + { + // Per the SSE parsing rules, only a single leading space is + // removed from a field value, and no trailing whitespace. + name: "data values keep all but one leading space", + input: "data: {\"a\":\ndata: 1}\n\n", + want: []Event{ + {Data: []byte("{\"a\":\n 1}")}, + }, + }, + { + name: "data value keeps trailing whitespace", + input: "data: hello \n\n", + want: []Event{ + {Data: []byte("hello ")}, + }, + }, + { + name: "field values keep all but one leading space", + input: "event: message\nid: 1 \nretry: 500\ndata: x\n\n", + want: []Event{ + {Name: " message", ID: "1 ", Retry: " 500", Data: []byte("x")}, + }, + }, } for _, tt := range tests {