refactor: Introduce AbstractClientTransport and simplify client transport lifecycle (#517) (#516)

## refactor: Introduce AbstractClientTransport and simplify client
transport lifecycle

This PR unifies state management logic across client transports, except
for the websocket transport, as it needs more refactoring first and is
not the primary transport.

- Introduce `AbstractClientTransport` as base class for other client
transports.
- Migrate to `ClientTransportState` states with state machine,
streamline state management.
- Ensure proper cleanup and error handling consistency across transport
implementations.
- Add unit tests to validate `AbstractClientTransport` behavior and
state transitions.
- Update related documentation and API contract.
- Make sure `onClose` callback is called at most once
- fix
[StreamableHttpClientTransportTest.kt‎](https://github.com/modelcontextprotocol/kotlin-sdk/pull/516/changes#diff-b9fe8891d08a492448a7ed2dc782151c6a915ae1403a4d70c2034c6062c84cb5)
to throw `McpException` on connect when received invalid Json

## Motivation and Context

Unify lifecycle handling and eliminate duplication in client Transport
implementations.


## How Has This Been Tested?
Unit test, regression tests

## Breaking Changes

- `onClose` callback is now called only once
- send(...) will throw McpException with message "Transport is not
ready" when `ClientTransportState != Operational`

## Types of changes

- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] Refactoring
- [ ] New feature (non-breaking change which adds functionality)
- [x] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update

## Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply. -->
- [x] I have read the [MCP
Documentation](https://modelcontextprotocol.io)
- [x] My code follows the repository's style guidelines
- [ ] New and existing tests pass locally
- [ ] I have added appropriate error handling
- [ ] I have added or updated documentation as needed

## Additional context
See #517
This commit is contained in:
Konstantin Pavlov 2026-02-13 13:08:26 +02:00 • committed by GitHub
commit 6120b3109e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 1057 additions and 191 deletions

View file

@ -0,0 +1,170 @@
package io.modelcontextprotocol.kotlin.sdk.client
import io.github.oshai.kotlinlogging.KLogger
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.client.HttpClient
import io.ktor.client.plugins.sse.ClientSSESession
import io.ktor.client.plugins.sse.sseSession
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.Url
import io.ktor.http.append
import io.ktor.http.isSuccess
import io.ktor.http.protocolWithAuthority
import io.modelcontextprotocol.kotlin.sdk.shared.AbstractClientTransport
import io.modelcontextprotocol.kotlin.sdk.shared.TransportSendOptions
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.McpJson
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.serialization.SerializationException
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.time.Duration
/**
* Client transport for SSE: this will connect to a server using Server-Sent Events for receiving
* messages and make separate POST requests for sending messages.
*/
@OptIn(ExperimentalAtomicApi::class)
public class SseClientTransport(
private val client: HttpClient,
private val urlString: String?,
private val reconnectionTime: Duration? = null,
private val requestBuilder: HttpRequestBuilder.() -> Unit = {},
) : AbstractClientTransport() {
override val logger: KLogger = KotlinLogging.logger {}
private val endpoint = CompletableDeferred<String>()
private lateinit var session: ClientSSESession
private lateinit var scope: CoroutineScope
private var job: Job? = null
private val baseUrl: String by lazy {
session.call.request.url.let { url ->
val path = url.encodedPath
when {
path.isEmpty() -> url.protocolWithAuthority
path.endsWith("/") -> url.protocolWithAuthority + path.removeSuffix("/")
else -> url.protocolWithAuthority + path.take(path.lastIndexOf("/"))
}
}
}
override suspend fun initialize() {
session = urlString?.let {
client.sseSession(
urlString = it,
reconnectionTime = reconnectionTime,
block = requestBuilder,
)
} ?: client.sseSession(
reconnectionTime = reconnectionTime,
block = requestBuilder,
)
scope = CoroutineScope(session.coroutineContext + SupervisorJob())
job = scope.launch(CoroutineName("SseMcpClientTransport.connect#${hashCode()}")) {
collectMessages()
}
endpoint.await()
}
@OptIn(ExperimentalCoroutinesApi::class)
override suspend fun performSend(message: JSONRPCMessage, options: TransportSendOptions?) {
check(job?.isActive == true) { "SseClientTransport is closed!" }
check(endpoint.isCompleted) { "Not connected!" }
val response = client.post(endpoint.getCompleted()) {
requestBuilder()
headers.append(HttpHeaders.ContentType, ContentType.Application.Json)
setBody(McpJson.encodeToString(message))
}
if (!response.status.isSuccess()) {
val text = response.bodyAsText()
error("Error POSTing to endpoint (HTTP ${response.status}): $text")
}
logger.debug { "Client successfully sent message via SSE $endpoint" }
}
private suspend fun CoroutineScope.collectMessages() {
try {
session.incoming.collect { event ->
ensureActive()
when (event.event) {
"error" -> {
val error = IllegalStateException("SSE error: ${event.data}")
_onError(error)
throw error
}
"open" -> {
// The connection is open, but we need to wait for the endpoint to be received.
}
"endpoint" -> handleEndpoint(event.data.orEmpty())
else -> handleMessage(event.data.orEmpty())
}
}
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
_onError(e)
throw e
} finally {
closeResources()
}
}
private fun handleEndpoint(eventData: String) {
try {
val path = if (eventData.startsWith("/")) eventData.substring(1) else eventData
val endpointUrl = Url("$baseUrl/$path")
endpoint.complete(endpointUrl.toString())
logger.debug { "Client connected to endpoint: $endpointUrl" }
} catch (e: Throwable) {
_onError(e)
endpoint.completeExceptionally(e)
throw e
}
}
private suspend fun handleMessage(data: String) {
try {
val message = McpJson.decodeFromString<JSONRPCMessage>(data)
_onMessage(message)
} catch (e: SerializationException) {
_onError(e)
}
}
override suspend fun closeResources() {
job?.cancelAndJoin()
try {
if (::session.isInitialized) session.cancel()
if (::scope.isInitialized) scope.cancel()
endpoint.cancel()
} catch (e: Throwable) {
_onError(e)
}
}
}

View file

@ -1,5 +1,6 @@
package io.modelcontextprotocol.kotlin.sdk.client
import io.github.oshai.kotlinlogging.KLogger
import io.github.oshai.kotlinlogging.KotlinLogging
import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport.StderrSeverity.DEBUG
import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport.StderrSeverity.FATAL
@ -7,7 +8,7 @@ import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport.StderrSeve
import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport.StderrSeverity.INFO
import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport.StderrSeverity.WARNING
import io.modelcontextprotocol.kotlin.sdk.internal.IODispatcher
import io.modelcontextprotocol.kotlin.sdk.shared.AbstractTransport
import io.modelcontextprotocol.kotlin.sdk.shared.AbstractClientTransport
import io.modelcontextprotocol.kotlin.sdk.shared.ReadBuffer
import io.modelcontextprotocol.kotlin.sdk.shared.TransportSendOptions
import io.modelcontextprotocol.kotlin.sdk.shared.serializeMessage
@ -39,7 +40,6 @@ import kotlinx.io.buffered
import kotlinx.io.readByteArray
import kotlinx.io.writeString
import kotlinx.serialization.SerializationException
import kotlin.concurrent.atomics.AtomicBoolean
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.coroutines.CoroutineContext
import kotlin.jvm.JvmOverloads
@ -88,7 +88,9 @@ public class StdioClientTransport @JvmOverloads public constructor(
private val error: Source? = null,
private val sendChannel: Channel<JSONRPCMessage> = Channel(Channel.BUFFERED),
private val classifyStderr: (String) -> StderrSeverity = { DEBUG },
) : AbstractTransport() {
) : AbstractClientTransport() {
override val logger: KLogger = KotlinLogging.logger {}
private companion object {
/**
@ -96,8 +98,6 @@ public class StdioClientTransport @JvmOverloads public constructor(
* 8KB is optimal for most systems (matches default page size).
*/
const val BUFFER_SIZE = 8 * 1024L
private val logger = KotlinLogging.logger {}
}
/**
@ -113,13 +113,8 @@ public class StdioClientTransport @JvmOverloads public constructor(
private val ioCoroutineContext: CoroutineContext = IODispatcher
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val initialized = AtomicBoolean(false)
private val onCloseCalled = AtomicBoolean(false)
override suspend fun start() {
if (!initialized.compareAndSet(expectedValue = false, newValue = true)) {
error("StdioClientTransport already started!")
}
override suspend fun initialize() {
logger.debug { "Starting StdioClientTransport..." }
// Producers run on IODispatcher for I/O
@ -224,24 +219,12 @@ public class StdioClientTransport @JvmOverloads public constructor(
// Wait for write job to complete before closing, matching old implementation
writeJob?.cancelAndJoin()
logger.debug { "Transport coroutine completed, calling onClose" }
callOnCloseOnce()
invokeOnCloseCallback()
}
}
}
override suspend fun send(message: JSONRPCMessage, options: TransportSendOptions?) {
if (!initialized.load()) {
throw McpException(
code = CONNECTION_CLOSED,
message = "Transport is not started",
)
}
if (onCloseCalled.load()) {
throw McpException(
code = CONNECTION_CLOSED,
message = "Transport is closed",
)
}
override suspend fun performSend(message: JSONRPCMessage, options: TransportSendOptions?) {
@Suppress("SwallowedException")
try {
sendChannel.send(message)
@ -254,33 +237,14 @@ public class StdioClientTransport @JvmOverloads public constructor(
message = "Transport is closed",
cause = e,
)
} catch (e: McpException) {
logger.debug(e) { "Error while sending message: ${e.message}" }
throw e
} catch (e: Throwable) {
logger.error(e) { "Error while sending message: ${e.message}" }
throw McpException(
code = INTERNAL_ERROR,
message = "Error while sending message: ${e.message}",
cause = e,
)
}
}
override suspend fun close() {
if (!initialized.compareAndSet(expectedValue = true, newValue = false)) {
return // Already closed
}
override suspend fun closeResources() {
scope.stopProcessing("Closed")
scope.coroutineContext[Job]?.join() // Wait for all coroutines to complete
}
private fun callOnCloseOnce() {
if (onCloseCalled.compareAndSet(expectedValue = false, newValue = true)) {
runCatching { _onClose() }
}
}
private fun sendOutboundMessage(message: JSONRPCMessage, sink: Sink, mainScope: CoroutineScope) {
try {
val json = serializeMessage(message)
@ -308,7 +272,7 @@ public class StdioClientTransport @JvmOverloads public constructor(
private fun CoroutineScope.stopProcessing(reason: String, cause: Throwable? = null) {
sendChannel.close() // Stop accepting new messages
callOnCloseOnce()
invokeOnCloseCallback()
cancel(reason, cause) // cancel current coroutine context
}

View file

@ -1,5 +1,6 @@
package io.modelcontextprotocol.kotlin.sdk.client
import io.github.oshai.kotlinlogging.KLogger
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.client.HttpClient
import io.ktor.client.plugins.sse.ClientSSESession
@ -21,15 +22,13 @@ import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.http.isSuccess
import io.ktor.utils.io.readUTF8Line
import io.modelcontextprotocol.kotlin.sdk.shared.AbstractTransport
import io.modelcontextprotocol.kotlin.sdk.shared.AbstractClientTransport
import io.modelcontextprotocol.kotlin.sdk.shared.TransportSendOptions
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.JSONRPCResponse
import io.modelcontextprotocol.kotlin.sdk.types.McpException
import io.modelcontextprotocol.kotlin.sdk.types.McpJson
import io.modelcontextprotocol.kotlin.sdk.types.RPCError.ErrorCode.CONNECTION_CLOSED
import io.modelcontextprotocol.kotlin.sdk.types.RequestId
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineName
@ -40,7 +39,6 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlin.concurrent.atomics.AtomicBoolean
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.time.Duration
@ -65,18 +63,14 @@ public class StreamableHttpClientTransport(
private val url: String,
private val reconnectionTime: Duration? = null,
private val requestBuilder: HttpRequestBuilder.() -> Unit = {},
) : AbstractTransport() {
) : AbstractClientTransport() {
private companion object {
private val logger = KotlinLogging.logger {}
}
override val logger: KLogger = KotlinLogging.logger {}
public var sessionId: String? = null
private set
public var protocolVersion: String? = null
private val initialized: AtomicBoolean = AtomicBoolean(false)
private var sseSession: ClientSSESession? = null
private var sseJob: Job? = null
@ -84,42 +78,21 @@ public class StreamableHttpClientTransport(
private var lastEventId: String? = null
override suspend fun start() {
if (!initialized.compareAndSet(expectedValue = false, newValue = true)) {
error("StreamableHttpClientTransport already started!")
}
logger.debug { "Client transport starting..." }
override suspend fun initialize() {
logger.debug { "Client transport is starting..." }
}
/**
* Sends a single message with optional resumption support
*/
override suspend fun send(message: JSONRPCMessage, options: TransportSendOptions?) {
send(message, options?.resumptionToken, options?.onResumptionToken)
}
/**
* Sends one or more messages with optional resumption support.
* This is the main send method that matches the TypeScript implementation.
*/
public suspend fun send(
message: JSONRPCMessage,
resumptionToken: String?,
onResumptionToken: ((String) -> Unit)? = null,
) {
if (!initialized.load()) {
throw McpException(
code = CONNECTION_CLOSED,
message = "Transport is not started",
)
}
override suspend fun performSend(message: JSONRPCMessage, options: TransportSendOptions?) {
logger.debug { "Client sending message via POST to $url: ${McpJson.encodeToString(message)}" }
// If we have a resumption token, reconnect the SSE stream with it
resumptionToken?.let { token ->
options?.resumptionToken?.let { token ->
startSseSession(
resumptionToken = token,
onResumptionToken = onResumptionToken,
onResumptionToken = options.onResumptionToken,
replayMessageId = if (message is JSONRPCRequest) message.id else null,
)
return
@ -138,7 +111,7 @@ public class StreamableHttpClientTransport(
if (response.status == HttpStatusCode.Accepted) {
if (message is JSONRPCNotification && message.method == "notifications/initialized") {
startSseSession(onResumptionToken = onResumptionToken)
startSseSession(onResumptionToken = options?.onResumptionToken)
}
return
}
@ -161,7 +134,7 @@ public class StreamableHttpClientTransport(
ContentType.Text.EventStream -> handleInlineSse(
response,
onResumptionToken = onResumptionToken,
onResumptionToken = options?.onResumptionToken,
replayMessageId = if (message is JSONRPCRequest) message.id else null,
)
@ -177,23 +150,31 @@ public class StreamableHttpClientTransport(
}
}
override suspend fun close() {
if (!initialized.load()) return // Already closed or never started
/**
* Sends one or more messages with optional resumption support.
* This is the main send method that matches the TypeScript implementation.
*/
public suspend fun send(
message: JSONRPCMessage,
resumptionToken: String?,
onResumptionToken: ((String) -> Unit)? = null,
): Unit = send(
message = message,
options = TransportSendOptions(
resumptionToken = resumptionToken,
onResumptionToken = onResumptionToken,
),
)
override suspend fun closeResources() {
logger.debug { "Client transport closing." }
try {
// Try to terminate session if we have one
terminateSession()
// Try to terminate session if we have one
terminateSession()
sseSession?.cancel()
sseJob?.cancelAndJoin()
scope.cancel()
} catch (_: Exception) {
// Ignore errors during cleanup
} finally {
initialized.store(false)
_onClose()
}
sseSession?.cancel()
sseJob?.cancelAndJoin()
scope.cancel()
}
/**

View file

@ -32,7 +32,7 @@ abstract class AbstractClientTransportLifecycleTest<T : AbstractTransport> {
val exception = shouldThrow<IllegalStateException> {
transport.start()
}
exception.message shouldContain "already started"
exception.message shouldContain "Can't change state: expected transport state"
}
@Test
@ -53,8 +53,8 @@ abstract class AbstractClientTransportLifecycleTest<T : AbstractTransport> {
val exception = shouldThrow<McpException> {
transport.send(PingRequest().toJSON())
}
exception.message shouldContain "not started"
exception.code shouldBe CONNECTION_CLOSED
exception.message shouldContain "Transport is not ready"
}
@Test

View file

@ -1,5 +1,6 @@
package io.modelcontextprotocol.kotlin.sdk.client.streamable.http
import io.kotest.matchers.shouldBe
import io.ktor.client.HttpClient
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.MockRequestHandler
@ -18,7 +19,9 @@ import io.modelcontextprotocol.kotlin.sdk.types.Implementation
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.McpException
import io.modelcontextprotocol.kotlin.sdk.types.McpJson
import io.modelcontextprotocol.kotlin.sdk.types.RPCError
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
@ -94,7 +97,11 @@ class StreamableHttpClientTransportTest {
)
val transport = createTransport { request ->
when (val msg = McpJson.decodeFromString<JSONRPCMessage>((request.body as TextContent).text)) {
when (
val msg = McpJson.decodeFromString<JSONRPCMessage>(
(request.body as TextContent).text,
)
) {
is JSONRPCRequest if msg.method == "initialize" -> respond(
content = "",
status = HttpStatusCode.OK,
@ -407,7 +414,7 @@ class StreamableHttpClientTransportTest {
try {
// Real time-keeping is needed; otherwise Protocol will always throw TimeoutCancellationException in tests
assertFailsWith<IllegalStateException>(
val mcpException = assertFailsWith<McpException>(
message = "Expected client.connect to fail on invalid JSON response",
) {
withContext(Dispatchers.Default.limitedParallelism(1)) {
@ -416,6 +423,7 @@ class StreamableHttpClientTransportTest {
}
}
}
mcpException.code shouldBe RPCError.ErrorCode.INTERNAL_ERROR
} finally {
transport.close()
}

View file

@ -166,18 +166,12 @@ class StdioClientTransportErrorHandlingTest {
true,
ErrorCode.INTERNAL_ERROR,
),
Arguments.of(
OutOfMemoryError(),
true,
ErrorCode.INTERNAL_ERROR,
),
)
}
@ParameterizedTest
@MethodSource("exceptions")
fun `Send should handle exceptions`(throwable: Throwable, shouldWrap: Boolean, expectedCode: Int?) = runTest {
fun `Send should handle exceptions`(throwable: Exception, shouldWrap: Boolean, expectedCode: Int?) = runTest {
val sendChannel: Channel<JSONRPCMessage> = mockk(relaxed = true)
// Create stdin pipe that stays open to prevent transport from closing