From 5cb76fd0401dc33ff279520456dfee62033f363e Mon Sep 17 00:00:00 2001 From: Pavel Gorgulov Date: Thu, 16 Jul 2026 15:41:46 +0200 Subject: [PATCH] fix(core): clear recently-cancelled request ids on connection close (#892) Clear the recently-cancelled request id buffer in `doClose` so connection teardown fully resets per-request bookkeeping. ## Motivation and Context Follow-up to #884. `doClose` already resets `_responseHandlers`, `_progressHandlers`, and `inFlightRequestJobs`, but left `recentlyCancelledRequestIds` populated across a close. This aligns teardown to clear all Protocol-scoped per-request state. Not a correctness bug: the buffer is bounded (256) and self-evicting, request ids are random UUIDs so stale entries cannot false-match a new connection, and the post-close `onMessage` guard drops late messages from the old transport before the buffer is consulted. The change removes the lone asymmetry in `doClose`. ## How Has This Been Tested? - `./gradlew :kotlin-sdk-core:compileKotlinJvm` - `./gradlew :kotlin-sdk-core:jvmTest --tests "*ProtocolTest*"` ## 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 - [ ] I have added appropriate error handling - [ ] I have added or updated documentation as needed ## Additional context `recentlyCancelledRequestIds` is Protocol-scoped (like `_responseHandlers`/`_progressHandlers`), so it is reset in `doClose` rather than on the per-connection `Connection` object. --- .../kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt b/kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt index 3515b4a..0c82f5e 100644 --- a/kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt +++ b/kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt @@ -436,6 +436,7 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio } val handlersToNotify = _responseHandlers.getAndSet(persistentMapOf()).values.toList() _progressHandlers.getAndSet(persistentMapOf()) + recentlyCancelledRequestIds.getAndSet(persistentListOf()) connection.inFlightRequestJobs.getAndSet(persistentMapOf()) connection.handlerScope.cancel() onClose()