From ee341df11e4413f8a7dbc68725612c3f48bfd1dc Mon Sep 17 00:00:00 2001 From: Pavel Gorgulov Date: Mon, 3 Nov 2025 16:36:53 +0100 Subject: [PATCH] Fix: Memory leak from unclosed sessions in Server (#359) ## Motivation and Context Sessions were added to the `sessions` list on connect but never removed when closed, causing a memory leak in long-running server processes. The closed sessions and their closures would accumulate indefinitely, preventing garbage collection. ## Breaking Changes None ## Types of changes - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update ## Checklist - [x] I have read the [MCP Documentation](https://modelcontextprotocol.io) - [x] My code follows the repository's style guidelines - [x] New and existing tests pass locally - [x] I have added appropriate error handling - [x] I have added or updated documentation as needed --- .../io/modelcontextprotocol/kotlin/sdk/server/Server.kt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/Server.kt b/kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/Server.kt index 15d61c1..04f18f8 100644 --- a/kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/Server.kt +++ b/kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/Server.kt @@ -169,6 +169,11 @@ public open class Server( } } + // Register cleanup handler to remove session from list when it closes + session.onClose { + logger.debug { "Removing closed session from active sessions list" } + sessions.update { list -> list - session } + } logger.debug { "Server session connecting to transport" } session.connect(transport) logger.debug { "Server session successfully connected to transport" }