From e761950d9795d120ce9b00e5ba87b93c30a7be90 Mon Sep 17 00:00:00 2001 From: George McCarron Date: Fri, 24 Jul 2026 09:07:06 +0100 Subject: [PATCH] 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) Co-authored-by: Yaroslav --- mcp/event.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/mcp/event.go b/mcp/event.go index 41ff4ae..bbb3e6c 100644 --- a/mcp/event.go +++ b/mcp/event.go @@ -52,7 +52,12 @@ func writeEvent(w http.ResponseWriter, evt Event) (int, error) { if evt.Retry != "" { fmt.Fprintf(&b, "retry: %s\n", evt.Retry) } - fmt.Fprintf(&b, "data: %s\n\n", string(evt.Data)) + // Write the payload directly into a pre-grown buffer to avoid the extra + // copy from string(evt.Data) and repeated buffer regrowths. + b.Grow(len("data: \n\n") + len(evt.Data)) + b.WriteString("data: ") + b.Write(evt.Data) + b.WriteString("\n\n") n, err := w.Write(b.Bytes()) rc := http.NewResponseController(w) // Ignore returned error as flushing is best-effort.