fix: propagate CancellationException instead of logging as error (#706)

fixes #242

## How Has This Been Tested?
new and existing tests pass

## 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
This commit is contained in:
Pavel Gorgulov 2026-04-15 14:59:01 +02:00 • committed by GitHub
commit e7b09d84f7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 109 additions and 25 deletions

View file

@ -24,11 +24,12 @@ import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.ensureActive import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerializationException import kotlinx.serialization.SerializationException
import kotlin.concurrent.atomics.ExperimentalAtomicApi import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.time.Duration import kotlin.time.Duration
@ -171,13 +172,15 @@ public class SseClientTransport(
} }
override suspend fun closeResources() { override suspend fun closeResources() {
job?.cancelAndJoin() withContext(NonCancellable) {
try { job?.cancel()
if (::session.isInitialized) session.cancel() try {
if (::scope.isInitialized) scope.cancel() if (::session.isInitialized) session.cancel()
endpoint.cancel() if (::scope.isInitialized) scope.cancel()
} catch (e: Throwable) { endpoint.cancel()
_onError(e) } catch (e: Throwable) {
_onError(e)
}
} }
} }
} }

View file

@ -21,6 +21,7 @@ import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.cancelAndJoin
@ -31,6 +32,7 @@ import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield import kotlinx.coroutines.yield
import kotlinx.io.Buffer import kotlinx.io.Buffer
import kotlinx.io.IOException import kotlinx.io.IOException
@ -241,8 +243,10 @@ public class StdioClientTransport @JvmOverloads public constructor(
} }
override suspend fun closeResources() { override suspend fun closeResources() {
scope.stopProcessing("Closed") withContext(NonCancellable) {
scope.coroutineContext[Job]?.join() // Wait for all coroutines to complete scope.stopProcessing("Closed")
scope.coroutineContext[Job]?.join() // Wait for all coroutines to complete
}
} }
private fun sendOutboundMessage(message: JSONRPCMessage, sink: Sink, mainScope: CoroutineScope) { private fun sendOutboundMessage(message: JSONRPCMessage, sink: Sink, mainScope: CoroutineScope) {
@ -264,6 +268,8 @@ public class StdioClientTransport @JvmOverloads public constructor(
private suspend fun handleJSONRPCMessage(msg: JSONRPCMessage) { private suspend fun handleJSONRPCMessage(msg: JSONRPCMessage) {
try { try {
_onMessage.invoke(msg) _onMessage.invoke(msg)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) { } catch (e: Throwable) {
logger.error(e) { "Error processing message." } logger.error(e) { "Error processing message." }
runCatching { _onError.invoke(e) } runCatching { _onError.invoke(e) }

View file

@ -277,12 +277,15 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
} }
try { try {
handler(notification) handler(notification)
} catch (e: CancellationException) {
throw e
} catch (cause: Throwable) { } catch (cause: Throwable) {
logger.error(cause) { "Error handling notification: ${notification.method}" } logger.error(cause) { "Error handling notification: ${notification.method}" }
onError(cause) onError(cause)
} }
} }
@Suppress("ThrowsCount")
private suspend fun onRequest(request: JSONRPCRequest) { private suspend fun onRequest(request: JSONRPCRequest) {
logger.trace { "Received request: ${request.method} (id: ${request.id})" } logger.trace { "Received request: ${request.method} (id: ${request.id})" }
@ -300,6 +303,8 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
), ),
), ),
) )
} catch (e: CancellationException) {
throw e
} catch (cause: Throwable) { } catch (cause: Throwable) {
logger.error(cause) { "Error sending method not found response" } logger.error(cause) { "Error sending method not found response" }
onError(cause) onError(cause)

View file

@ -16,6 +16,7 @@ import kotlinx.coroutines.job
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlin.concurrent.atomics.AtomicBoolean import kotlin.concurrent.atomics.AtomicBoolean
import kotlin.concurrent.atomics.ExperimentalAtomicApi import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.coroutines.cancellation.CancellationException
/** WebSocket subprotocol identifier for MCP connections. */ /** WebSocket subprotocol identifier for MCP connections. */
public const val MCP_SUBPROTOCOL: String = "mcp" public const val MCP_SUBPROTOCOL: String = "mcp"
@ -44,6 +45,7 @@ public abstract class WebSocketMcpTransport : AbstractTransport() {
*/ */
protected abstract suspend fun initializeSession() protected abstract suspend fun initializeSession()
@Suppress("ThrowsCount")
override suspend fun start() { override suspend fun start() {
logger.debug { "Starting websocket transport" } logger.debug { "Starting websocket transport" }
@ -74,6 +76,8 @@ public abstract class WebSocketMcpTransport : AbstractTransport() {
try { try {
val message = McpJson.decodeFromString<JSONRPCMessage>(message.readText()) val message = McpJson.decodeFromString<JSONRPCMessage>(message.readText())
_onMessage.invoke(message) _onMessage.invoke(message)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
_onError.invoke(e) _onError.invoke(e)
throw e throw e

View file

@ -1,11 +1,14 @@
package io.modelcontextprotocol.kotlin.sdk.shared package io.modelcontextprotocol.kotlin.sdk.shared
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldBe
import io.modelcontextprotocol.kotlin.sdk.types.CustomRequest import io.modelcontextprotocol.kotlin.sdk.types.CustomRequest
import io.modelcontextprotocol.kotlin.sdk.types.EmptyResult import io.modelcontextprotocol.kotlin.sdk.types.EmptyResult
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCNotification
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCRequest import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCRequest
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCResponse import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCResponse
import io.modelcontextprotocol.kotlin.sdk.types.McpJson import io.modelcontextprotocol.kotlin.sdk.types.McpJson
@ -24,6 +27,7 @@ import kotlinx.serialization.json.encodeToJsonElement
import kotlinx.serialization.json.int import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.jsonPrimitive
import kotlin.coroutines.cancellation.CancellationException
import kotlin.test.BeforeTest import kotlin.test.BeforeTest
import kotlin.test.Test import kotlin.test.Test
@ -126,6 +130,36 @@ class ProtocolTest {
inFlight.await() inFlight.await()
} }
@Test
fun `should propagate CancellationException from notification handler without calling onError`() = runTest {
protocol.connect(transport)
protocol.fallbackNotificationHandler = {
throw CancellationException("test cancellation")
}
shouldThrow<CancellationException> {
transport.deliver(JSONRPCNotification(method = "test/notification"))
}
protocol.errors shouldHaveSize 0
}
@Test
fun `should report non-cancellation exception from notification handler via onError`() = runTest {
protocol.connect(transport)
protocol.fallbackNotificationHandler = {
throw IllegalStateException("handler failed")
}
// Non-CE exceptions are caught and reported, not propagated
transport.deliver(JSONRPCNotification(method = "test/notification"))
protocol.errors shouldHaveSize 1
protocol.errors[0].message shouldBe "handler failed"
}
@Test @Test
fun `should create params object when request params are null`() = runTest { fun `should create params object when request params are null`() = runTest {
protocol.connect(transport) protocol.connect(transport)
@ -154,6 +188,12 @@ class ProtocolTest {
} }
private class TestProtocol : Protocol(null) { private class TestProtocol : Protocol(null) {
val errors = mutableListOf<Throwable>()
override fun onError(error: Throwable) {
errors.add(error)
}
override fun assertCapabilityForMethod(method: Method) { override fun assertCapabilityForMethod(method: Method) {
// noop // noop
} }

View file

@ -84,6 +84,8 @@ public class SseServerTransport(private val endpoint: String, private val sessio
} }
call.receiveText() call.receiveText()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
call.respondText("Invalid message: ${e.message}", status = HttpStatusCode.BadRequest) call.respondText("Invalid message: ${e.message}", status = HttpStatusCode.BadRequest)
_onError.invoke(e) _onError.invoke(e)
@ -92,6 +94,8 @@ public class SseServerTransport(private val endpoint: String, private val sessio
try { try {
handleMessage(body) handleMessage(body)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
call.respondText("Error handling message $body: ${e.message}", status = HttpStatusCode.BadRequest) call.respondText("Error handling message $body: ${e.message}", status = HttpStatusCode.BadRequest)
return return
@ -108,6 +112,8 @@ public class SseServerTransport(private val endpoint: String, private val sessio
try { try {
val parsedMessage = McpJson.decodeFromString<JSONRPCMessage>(message) val parsedMessage = McpJson.decodeFromString<JSONRPCMessage>(message)
_onMessage.invoke(parsedMessage) _onMessage.invoke(parsedMessage)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
_onError.invoke(e) _onError.invoke(e)
throw e throw e

View file

@ -28,15 +28,18 @@ import io.modelcontextprotocol.kotlin.sdk.types.RPCError
import io.modelcontextprotocol.kotlin.sdk.types.RPCError.ErrorCode.REQUEST_TIMEOUT import io.modelcontextprotocol.kotlin.sdk.types.RPCError.ErrorCode.REQUEST_TIMEOUT
import io.modelcontextprotocol.kotlin.sdk.types.RequestId import io.modelcontextprotocol.kotlin.sdk.types.RequestId
import io.modelcontextprotocol.kotlin.sdk.types.SUPPORTED_PROTOCOL_VERSIONS import io.modelcontextprotocol.kotlin.sdk.types.SUPPORTED_PROTOCOL_VERSIONS
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.job import kotlinx.coroutines.job
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.decodeFromJsonElement
import kotlin.concurrent.atomics.AtomicBoolean import kotlin.concurrent.atomics.AtomicBoolean
import kotlin.concurrent.atomics.ExperimentalAtomicApi import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Duration import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.milliseconds
import kotlin.uuid.ExperimentalUuidApi import kotlin.uuid.ExperimentalUuidApi
@ -283,17 +286,19 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
} }
override suspend fun close() { override suspend fun close() {
streamMutex.withLock { withContext(NonCancellable) {
streamsMapping.values.forEach { streamMutex.withLock {
try { streamsMapping.values.forEach {
it.session?.close() try {
} catch (_: Exception) { it.session?.close()
} catch (_: Exception) {
}
} }
streamsMapping.clear()
requestToStreamMapping.clear()
requestToResponseMapping.clear()
invokeOnCloseCallback()
} }
streamsMapping.clear()
requestToStreamMapping.clear()
requestToResponseMapping.clear()
invokeOnCloseCallback()
} }
} }
@ -420,6 +425,8 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
call.coroutineContext.job.invokeOnCompletion { streamsMapping.remove(streamId) } call.coroutineContext.job.invokeOnCompletion { streamsMapping.remove(streamId) }
messages.forEach { message -> _onMessage(message) } messages.forEach { message -> _onMessage(message) }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
call.reject( call.reject(
HttpStatusCode.BadRequest, HttpStatusCode.BadRequest,
@ -498,12 +505,14 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
val streamId = requestToStreamMapping[requestId] ?: return val streamId = requestToStreamMapping[requestId] ?: return
val sessionContext = streamsMapping[streamId] ?: return val sessionContext = streamsMapping[streamId] ?: return
try { withContext(NonCancellable) {
sessionContext.session?.close() try {
} catch (e: Exception) { sessionContext.session?.close()
_onError(e) } catch (e: Exception) {
} finally { _onError(e)
streamsMapping.remove(streamId) } finally {
streamsMapping.remove(streamId)
}
} }
} }
@ -554,6 +563,8 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
id = eventId, id = eventId,
data = McpJson.encodeToString(message), data = McpJson.encodeToString(message),
) )
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
_onError(IllegalStateException("Failed to replay event: ${e.message}", e)) _onError(IllegalStateException("Failed to replay event: ${e.message}", e))
} }
@ -565,6 +576,8 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
streamsMapping.remove(streamId) streamsMapping.remove(streamId)
throwable?.let { _onError(it) } throwable?.let { _onError(it) }
} }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
_onError(e) _onError(e)
} }
@ -658,6 +671,8 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
private suspend fun flushSse(session: ServerSSESession?) { private suspend fun flushSse(session: ServerSSESession?) {
try { try {
session?.send(data = "") session?.send(data = "")
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
_onError(e) _onError(e)
} }
@ -709,6 +724,9 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
val eventId = configuration.eventStore?.storeEvent(streamId, message) val eventId = configuration.eventStore?.storeEvent(streamId, message)
try { try {
session?.send(event = "message", id = eventId, data = McpJson.encodeToString(message)) session?.send(event = "message", id = eventId, data = McpJson.encodeToString(message))
} catch (e: CancellationException) {
streamsMapping.remove(streamId)
throw e
} catch (_: Exception) { } catch (_: Exception) {
streamsMapping.remove(streamId) streamsMapping.remove(streamId)
} }
@ -733,6 +751,8 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
retry = configuration.retryInterval?.inWholeMilliseconds, retry = configuration.retryInterval?.inWholeMilliseconds,
data = "", data = "",
) )
} catch (e: CancellationException) {
throw e
} catch (e: Exception) { } catch (e: Exception) {
_onError(e) _onError(e)
} }