Skip to content

Commit e761950

Browse files
george1410claudeyarolegovich
authored
mcp: avoid double-copy of payload in writeEvent (#1106)
`writeEvent` built the SSE frame with `fmt.Fprintf(&b, "data: %s\n\n", string(evt.Data))`, which copies the payload into a fresh string and then again into the buffer, growing it via repeated `bytes.growSlice` doublings. For large MCP responses (e.g. ~162KB `tools/list`) under a burst of concurrent writes this ~3x amplifies allocations and peak heap. Write the payload directly into a pre-grown buffer instead. Output framing is byte-identical. Benchmarks (162KB payload): 517KB->172KB per op, 9->4 allocs/op, ~3x faster. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Yaroslav <yarolegovich@gmail.com>
1 parent 2781b8f commit e761950

1 file changed

Lines changed: 6 additions & 1 deletion

File tree

mcp/event.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,12 @@ func writeEvent(w http.ResponseWriter, evt Event) (int, error) {
5252
if evt.Retry != "" {
5353
fmt.Fprintf(&b, "retry: %s\n", evt.Retry)
5454
}
55-
fmt.Fprintf(&b, "data: %s\n\n", string(evt.Data))
55+
// Write the payload directly into a pre-grown buffer to avoid the extra
56+
// copy from string(evt.Data) and repeated buffer regrowths.
57+
b.Grow(len("data: \n\n") + len(evt.Data))
58+
b.WriteString("data: ")
59+
b.Write(evt.Data)
60+
b.WriteString("\n\n")
5661
n, err := w.Write(b.Bytes())
5762
rc := http.NewResponseController(w)
5863
// Ignore returned error as flushing is best-effort.

0 commit comments

Comments
 (0)