Skip to content

Commit 1bdfcd6

Browse files
younsldimetron
andauthored
fix: release MCP session state so the server stops leaking heap (#85)
* fix: release MCP session state so the server stops leaking heap The streamable HTTP server registers a session on `initialize` and, on mcp-go v0.43.2, never releases it: `handleDelete` clears the per-session stores but never calls `UnregisterSession`, so every session a client ever opened is retained. A POST-only client leaks roughly 8 KB per initialize, which in production shows up as linear heap growth until the container is OOMKilled. Bump mcp-go to v1.1.0, which unregisters the session on DELETE, and enable its idle sweeper so sessions abandoned without a DELETE are reclaimed too. The sweeper is opt-in even on v1.1.0, so the bump alone is not enough. The new `--session-idle-ttl` flag defaults to 10m and 0 disables it. Shutdown now stops the sweeper and closes sessions that are still registered. Measured over repeated bursts of 500 initialize requests, 15s apart: mcp-go v0.43.2 3.44 -> 7.74 -> 12.96 -> 17.96 -> 21.65 MB live heap this change 3.93 -> 9.55 -> 9.63 -> 9.55 -> 9.55 MB live heap Closes #84 Signed-off-by: younsl <cysl@kakao.com> * test: run the cmd package tests in make test `make test` covered ./pkg/... and ./internal/... only, so the tests in cmd/ never ran in CI. That includes the session lifecycle regression tests this branch adds, which is the code path that leaked. Signed-off-by: younsl <cysl@kakao.com> --------- Signed-off-by: younsl <cysl@kakao.com> Co-authored-by: Dmytro Rashko <dimetron@me.com>
1 parent bd6e49d commit 1bdfcd6

6 files changed

Lines changed: 198 additions & 31 deletions

File tree

‎Makefile‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,11 @@ tidy: ## Run go mod tidy to ensure dependencies are up to date.
5858

5959
.PHONY: test
6060
test: build lint ## Run all tests with build, lint, and coverage
61-
go test -tags=test -v -cover ./pkg/... ./internal/...
61+
go test -tags=test -v -cover ./cmd/... ./pkg/... ./internal/...
6262

6363
.PHONY: test-only
6464
test-only: ## Run tests only (without build/lint for faster iteration)
65-
go test -tags=test -v -cover ./pkg/... ./internal/...
65+
go test -tags=test -v -cover ./cmd/... ./pkg/... ./internal/...
6666

6767
.PHONY: e2e
6868
e2e: test retag

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ The server runs using sse transport for MCP communication.
197197
| `--stdio` | `false` | Use stdio for communication instead of HTTP |
198198
| `--tools` | `[]` (all) | Comma-separated list of tool providers to register |
199199
| `--read-only` | `false` | Disable tools that perform write operations |
200+
| `--session-idle-ttl` | `10m` | Reclaim streamable HTTP session state after this idle duration (`0` disables the sweeper) |
200201
| `--kubeconfig` | `""` | Path to kubeconfig file (defaults to in-cluster config) |
201202
| `--version`, `-v` | `false` | Show version information and exit |
202203

‎cmd/main.go‎

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ var (
4646
showVersion bool
4747
readOnly bool
4848

49+
sessionIdleTTL time.Duration
50+
4951
// These variables should be set during build time using -ldflags
5052
Name = "kagent-tools-server"
5153
Version = version.Version
@@ -66,6 +68,7 @@ func init() {
6668
rootCmd.Flags().StringSliceVar(&tools, "tools", []string{}, "List of tools to register. If empty, all tools are registered.")
6769
rootCmd.Flags().BoolVarP(&showVersion, "version", "v", false, "Show version information and exit")
6870
rootCmd.Flags().BoolVar(&readOnly, "read-only", false, "Run in read-only mode (disable tools that perform write operations)")
71+
rootCmd.Flags().DurationVar(&sessionIdleTTL, "session-idle-ttl", 10*time.Minute, "Reclaim streamable HTTP session state after this idle duration (0 disables the sweeper)")
6972
kubeconfig = rootCmd.Flags().String("kubeconfig", "", "kubeconfig file path (optional, defaults to in-cluster config)")
7073

7174
// if found .env file, load it
@@ -160,7 +163,8 @@ func run(cmd *cobra.Command, args []string) {
160163

161164
// HTTP server reference (only used when not in stdio mode)
162165
var httpServer *http.Server
163-
var metricsServer *http.Server // Separate server for metrics if metricsPort is different from main port
166+
var metricsServer *http.Server // Separate server for metrics if metricsPort is different from main port
167+
var streamableServer *server.StreamableHTTPServer // Streamable HTTP transport, shut down to stop its session sweeper
164168

165169
// Start server based on chosen mode
166170
wg.Add(1)
@@ -170,9 +174,7 @@ func run(cmd *cobra.Command, args []string) {
170174
runStdioServer(ctx, mcp)
171175
}()
172176
} else {
173-
sseServer := server.NewStreamableHTTPServer(mcp,
174-
server.WithHeartbeatInterval(30*time.Second),
175-
)
177+
streamableServer = newStreamableHTTPServer(mcp, sessionIdleTTL)
176178

177179
// Create a mux to handle different routes
178180
mux := http.NewServeMux()
@@ -198,9 +200,7 @@ func run(cmd *cobra.Command, args []string) {
198200
Handler: metricsMux,
199201
}
200202

201-
wg.Add(1)
202-
go func() {
203-
defer wg.Done()
203+
wg.Go(func() {
204204
logger.Get().Info("Starting Prometheus metrics endpoint on /metrics", "port", strconv.Itoa(metricsPort))
205205
if err := metricsServer.ListenAndServe(); err != nil {
206206
if !errors.Is(err, http.ErrServerClosed) {
@@ -209,7 +209,7 @@ func run(cmd *cobra.Command, args []string) {
209209
logger.Get().Info("Metrics server closed gracefully.")
210210
}
211211
}
212-
}()
212+
})
213213
} else {
214214
logger.Get().Info("Starting Prometheus metrics endpoint on /metrics", "port", strconv.Itoa(port))
215215
mux.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
@@ -222,7 +222,7 @@ func run(cmd *cobra.Command, args []string) {
222222

223223
// Handle all other routes with the MCP server wrapped in telemetry middleware
224224
mux.Handle("/", telemetry.HTTPMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
225-
sseServer.ServeHTTP(w, r)
225+
streamableServer.ServeHTTP(w, r)
226226
})))
227227

228228
httpServer = &http.Server{
@@ -232,7 +232,7 @@ func run(cmd *cobra.Command, args []string) {
232232

233233
go func() {
234234
defer wg.Done()
235-
logger.Get().Info("Running KAgent Tools Server", "port", fmt.Sprintf(":%d", port), "tools", strings.Join(tools, ","))
235+
logger.Get().Info("Running KAgent Tools Server", "port", fmt.Sprintf(":%d", port), "tools", strings.Join(tools, ","), "session_idle_ttl", sessionIdleTTL.String())
236236
if err := httpServer.ListenAndServe(); err != nil {
237237
if !errors.Is(err, http.ErrServerClosed) {
238238
logger.Get().Error("Failed to start HTTP server", "error", err)
@@ -268,6 +268,18 @@ func run(cmd *cobra.Command, args []string) {
268268
}
269269
}
270270

271+
// Stop the session sweeper and close sessions still registered with the
272+
// MCP server, so nothing outlives the transport it belonged to
273+
if !stdio && streamableServer != nil {
274+
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
275+
defer shutdownCancel()
276+
277+
if err := streamableServer.Shutdown(shutdownCtx); err != nil {
278+
logger.Get().Error("Failed to shutdown MCP streamable HTTP server gracefully", "error", err)
279+
rootSpan.RecordError(err)
280+
}
281+
}
282+
271283
// Gracefully shutdown metrics server if running separately
272284
if !stdio && metricsServer != nil {
273285
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -287,6 +299,19 @@ func run(cmd *cobra.Command, args []string) {
287299
logger.Get().Info("Server shutdown complete")
288300
}
289301

302+
// newStreamableHTTPServer builds the streamable HTTP transport.
303+
//
304+
// A session is registered on `initialize` and released only when the client
305+
// sends DELETE, so a client that goes away without one leaves its session
306+
// behind forever. idleTTL bounds that by reclaiming sessions that have seen no
307+
// traffic for that long; zero or less disables the sweeper.
308+
func newStreamableHTTPServer(mcpServer *server.MCPServer, idleTTL time.Duration) *server.StreamableHTTPServer {
309+
return server.NewStreamableHTTPServer(mcpServer,
310+
server.WithHeartbeatInterval(30*time.Second),
311+
server.WithSessionIdleTTL(idleTTL),
312+
)
313+
}
314+
290315
// writeResponse writes data to an HTTP response writer with proper error handling
291316
func writeResponse(w http.ResponseWriter, data []byte) error {
292317
_, err := w.Write(data)

‎cmd/streamable_http_test.go‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"net/http"
6+
"net/http/httptest"
7+
"strings"
8+
"sync"
9+
"testing"
10+
"time"
11+
12+
"github.com/mark3labs/mcp-go/server"
13+
)
14+
15+
const initializeRequest = `{"jsonrpc":"2.0","id":1,"method":"initialize",` +
16+
`"params":{"protocolVersion":"2025-03-26","capabilities":{},` +
17+
`"clientInfo":{"name":"test","version":"1"}}}`
18+
19+
// sessionRecorder counts the sessions the MCP server registers and releases.
20+
// A session that is registered but never unregistered is retained state, which
21+
// is what leaks when a client never sends DELETE.
22+
type sessionRecorder struct {
23+
mu sync.Mutex
24+
registered int
25+
unregistered int
26+
}
27+
28+
func (r *sessionRecorder) hooks() *server.Hooks {
29+
hooks := &server.Hooks{}
30+
hooks.AddOnRegisterSession(func(_ context.Context, _ server.ClientSession) {
31+
r.mu.Lock()
32+
defer r.mu.Unlock()
33+
r.registered++
34+
})
35+
hooks.AddOnUnregisterSession(func(_ context.Context, _ server.ClientSession) {
36+
r.mu.Lock()
37+
defer r.mu.Unlock()
38+
r.unregistered++
39+
})
40+
return hooks
41+
}
42+
43+
func (r *sessionRecorder) counts() (int, int) {
44+
r.mu.Lock()
45+
defer r.mu.Unlock()
46+
return r.registered, r.unregistered
47+
}
48+
49+
// newRecordedServer starts the streamable HTTP transport wired exactly as the
50+
// server wires it, with session hooks attached.
51+
func newRecordedServer(t *testing.T, idleTTL time.Duration) (*httptest.Server, *sessionRecorder) {
52+
t.Helper()
53+
54+
recorder := &sessionRecorder{}
55+
mcpServer := server.NewMCPServer("test-server", "test", server.WithHooks(recorder.hooks()))
56+
streamableServer := newStreamableHTTPServer(mcpServer, idleTTL)
57+
t.Cleanup(func() {
58+
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
59+
defer cancel()
60+
_ = streamableServer.Shutdown(shutdownCtx)
61+
})
62+
63+
httpServer := httptest.NewServer(streamableServer)
64+
t.Cleanup(httpServer.Close)
65+
return httpServer, recorder
66+
}
67+
68+
// initializeSession sends an initialize request and returns the session ID the
69+
// server assigned to it.
70+
func initializeSession(t *testing.T, httpServer *httptest.Server) string {
71+
t.Helper()
72+
73+
req, err := http.NewRequest(http.MethodPost, httpServer.URL, strings.NewReader(initializeRequest))
74+
if err != nil {
75+
t.Fatalf("build initialize request: %v", err)
76+
}
77+
req.Header.Set("Content-Type", "application/json")
78+
req.Header.Set("Accept", "application/json, text/event-stream")
79+
80+
resp, err := httpServer.Client().Do(req)
81+
if err != nil {
82+
t.Fatalf("send initialize request: %v", err)
83+
}
84+
defer resp.Body.Close()
85+
86+
if resp.StatusCode != http.StatusOK {
87+
t.Fatalf("initialize returned status %d, want %d", resp.StatusCode, http.StatusOK)
88+
}
89+
sessionID := resp.Header.Get("Mcp-Session-Id")
90+
if sessionID == "" {
91+
t.Fatal("initialize response carried no Mcp-Session-Id header")
92+
}
93+
return sessionID
94+
}
95+
96+
// waitForUnregistered polls until the expected number of sessions has been
97+
// released, so the sweeper's own tick interval does not make the test flaky.
98+
func waitForUnregistered(t *testing.T, recorder *sessionRecorder, want int, timeout time.Duration) {
99+
t.Helper()
100+
101+
deadline := time.Now().Add(timeout)
102+
for {
103+
_, unregistered := recorder.counts()
104+
if unregistered >= want {
105+
return
106+
}
107+
if time.Now().After(deadline) {
108+
t.Fatalf("released %d sessions after %s, want %d", unregistered, timeout, want)
109+
}
110+
time.Sleep(20 * time.Millisecond)
111+
}
112+
}
113+
114+
// A client that ends its session explicitly must have it released.
115+
func TestStreamableHTTPServerReleasesSessionOnDelete(t *testing.T) {
116+
httpServer, recorder := newRecordedServer(t, 0)
117+
sessionID := initializeSession(t, httpServer)
118+
119+
if registered, _ := recorder.counts(); registered != 1 {
120+
t.Fatalf("registered %d sessions, want 1", registered)
121+
}
122+
123+
req, err := http.NewRequest(http.MethodDelete, httpServer.URL, nil)
124+
if err != nil {
125+
t.Fatalf("build delete request: %v", err)
126+
}
127+
req.Header.Set("Mcp-Session-Id", sessionID)
128+
129+
resp, err := httpServer.Client().Do(req)
130+
if err != nil {
131+
t.Fatalf("send delete request: %v", err)
132+
}
133+
defer resp.Body.Close()
134+
135+
if resp.StatusCode != http.StatusOK {
136+
t.Fatalf("delete returned status %d, want %d", resp.StatusCode, http.StatusOK)
137+
}
138+
waitForUnregistered(t, recorder, 1, 2*time.Second)
139+
}
140+
141+
// A client that goes away without a DELETE must not retain its session: the
142+
// idle sweeper is what bounds memory for POST-only clients.
143+
func TestStreamableHTTPServerSweepsIdleSession(t *testing.T) {
144+
httpServer, recorder := newRecordedServer(t, 100*time.Millisecond)
145+
initializeSession(t, httpServer)
146+
147+
if registered, _ := recorder.counts(); registered != 1 {
148+
t.Fatalf("registered %d sessions, want 1", registered)
149+
}
150+
waitForUnregistered(t, recorder, 1, 10*time.Second)
151+
}

‎go.mod‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ require (
66
github.com/joho/godotenv v1.5.1
77
github.com/kubescape/k8s-interface v0.0.203
88
github.com/kubescape/storage v0.0.239
9-
github.com/mark3labs/mcp-go v0.43.2
9+
github.com/mark3labs/mcp-go v1.1.0
1010
github.com/onsi/ginkgo/v2 v2.27.2
1111
github.com/onsi/gomega v1.38.2
1212
github.com/prometheus/client_golang v1.23.2
@@ -38,13 +38,11 @@ require (
3838
github.com/armosec/gojay v1.2.17 // indirect
3939
github.com/armosec/utils-go v0.0.58 // indirect
4040
github.com/armosec/utils-k8s-go v0.0.35 // indirect
41-
github.com/bahlo/generic-list-go v0.2.0 // indirect
4241
github.com/becheran/wildmatch-go v1.0.0 // indirect
4342
github.com/beorn7/perks v1.0.1 // indirect
4443
github.com/blang/semver/v4 v4.0.0 // indirect
4544
github.com/bmatcuk/doublestar/v4 v4.9.1 // indirect
4645
github.com/briandowns/spinner v1.23.2 // indirect
47-
github.com/buger/jsonparser v1.1.2 // indirect
4846
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
4947
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
5048
github.com/cespare/xxhash/v2 v2.3.0 // indirect
@@ -99,21 +97,20 @@ require (
9997
github.com/google/gnostic-models v0.7.1 // indirect
10098
github.com/google/go-cmp v0.7.0 // indirect
10199
github.com/google/go-containerregistry v0.20.6 // indirect
100+
github.com/google/jsonschema-go v0.4.2 // indirect
102101
github.com/google/licensecheck v0.3.1 // indirect
103102
github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8 // indirect
104103
github.com/google/uuid v1.6.0 // indirect
105104
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
106105
github.com/hashicorp/errwrap v1.1.0 // indirect
107106
github.com/hashicorp/go-multierror v1.1.1 // indirect
108107
github.com/inconshreveable/mousetrap v1.1.0 // indirect
109-
github.com/invopop/jsonschema v0.13.0 // indirect
110108
github.com/jinzhu/copier v0.4.0 // indirect
111109
github.com/json-iterator/go v1.1.12 // indirect
112110
github.com/klauspost/compress v1.18.4 // indirect
113111
github.com/kubescape/go-logger v0.0.26 // indirect
114112
github.com/kylelemons/godebug v1.1.0 // indirect
115113
github.com/mackerelio/go-osstat v0.2.6 // indirect
116-
github.com/mailru/easyjson v0.9.1 // indirect
117114
github.com/mattn/go-colorable v0.1.14 // indirect
118115
github.com/mattn/go-isatty v0.0.20 // indirect
119116
github.com/mitchellh/go-homedir v1.1.0 // indirect
@@ -133,6 +130,7 @@ require (
133130
github.com/prometheus/common v0.67.5 // indirect
134131
github.com/prometheus/procfs v0.19.2 // indirect
135132
github.com/sagikazarmark/locafero v0.12.0 // indirect
133+
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
136134
github.com/sasha-s/go-deadlock v0.3.6 // indirect
137135
github.com/scylladb/go-set v1.0.3-0.20200225121959-cc7b2070d91e // indirect
138136
github.com/seccomp/libseccomp-golang v0.10.0 // indirect
@@ -153,7 +151,6 @@ require (
153151
github.com/vishvananda/netns v0.0.5 // indirect
154152
github.com/wagoodman/go-partybus v0.0.0-20230516145632-8ccac152c651 // indirect
155153
github.com/wagoodman/go-progress v0.0.0-20230925121702-07e42b3cdba0 // indirect
156-
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
157154
github.com/x448/float16 v0.8.4 // indirect
158155
github.com/yl2chen/cidranger v1.0.2 // indirect
159156
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
@@ -188,7 +185,6 @@ require (
188185
google.golang.org/protobuf v1.36.12 // indirect
189186
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
190187
gopkg.in/inf.v0 v0.9.1 // indirect
191-
gopkg.in/yaml.v3 v3.0.1 // indirect
192188
k8s.io/apiserver v0.35.3 // indirect
193189
k8s.io/component-base v0.35.3 // indirect
194190
k8s.io/klog/v2 v2.130.1 // indirect

0 commit comments

Comments
 (0)