## 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:
parent
99908beb2a
commit
6120b3109e
8 changed files with 1057 additions and 191 deletions
|
|
@ -0,0 +1,49 @@
|
|||
package io.modelcontextprotocol.kotlin.sdk
|
||||
|
||||
import kotlin.annotation.AnnotationTarget.ANNOTATION_CLASS
|
||||
import kotlin.annotation.AnnotationTarget.CLASS
|
||||
import kotlin.annotation.AnnotationTarget.CONSTRUCTOR
|
||||
import kotlin.annotation.AnnotationTarget.FIELD
|
||||
import kotlin.annotation.AnnotationTarget.FUNCTION
|
||||
import kotlin.annotation.AnnotationTarget.LOCAL_VARIABLE
|
||||
import kotlin.annotation.AnnotationTarget.PROPERTY
|
||||
import kotlin.annotation.AnnotationTarget.PROPERTY_GETTER
|
||||
import kotlin.annotation.AnnotationTarget.PROPERTY_SETTER
|
||||
import kotlin.annotation.AnnotationTarget.TYPEALIAS
|
||||
import kotlin.annotation.AnnotationTarget.VALUE_PARAMETER
|
||||
|
||||
/**
|
||||
* Denotes that the annotated API is internal to the MCP SDK and its usage is restricted to components
|
||||
* within the SDK. It is not intended to be used in general application code or by external consumers.
|
||||
*
|
||||
* This annotation is used to communicate and enforce the limited visibility of certain APIs to prevent
|
||||
* accidental usage outside their intended context.
|
||||
*
|
||||
* Applying this annotation requires consumers to explicitly opt-in, acknowledging the warning level
|
||||
* associated with its use.
|
||||
*
|
||||
* This annotation can be used on classes, annotations, properties, fields, local variables, value
|
||||
* parameters, constructors, functions, property accessors, and type aliases.
|
||||
*
|
||||
* The annotation is retained in the binary and must be documented.
|
||||
*/
|
||||
@RequiresOptIn(
|
||||
message = "This API is internal, and its usage is restricted to internal components of the MCP SDK.",
|
||||
level = RequiresOptIn.Level.WARNING,
|
||||
)
|
||||
@MustBeDocumented
|
||||
@Target(
|
||||
CLASS,
|
||||
ANNOTATION_CLASS,
|
||||
PROPERTY,
|
||||
FIELD,
|
||||
LOCAL_VARIABLE,
|
||||
VALUE_PARAMETER,
|
||||
CONSTRUCTOR,
|
||||
FUNCTION,
|
||||
PROPERTY_GETTER,
|
||||
PROPERTY_SETTER,
|
||||
TYPEALIAS,
|
||||
)
|
||||
@Retention(AnnotationRetention.BINARY)
|
||||
public annotation class InternalMcpApi
|
||||
|
|
@ -0,0 +1,274 @@
|
|||
package io.modelcontextprotocol.kotlin.sdk.shared
|
||||
|
||||
import io.github.oshai.kotlinlogging.KLogger
|
||||
import io.modelcontextprotocol.kotlin.sdk.InternalMcpApi
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.McpException
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.RPCError.ErrorCode.CONNECTION_CLOSED
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.RPCError.ErrorCode.INTERNAL_ERROR
|
||||
import kotlin.concurrent.atomics.AtomicReference
|
||||
import kotlin.concurrent.atomics.ExperimentalAtomicApi
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
|
||||
/**
|
||||
* Abstract base class representing a client-side transport layer for communication.
|
||||
*
|
||||
* This class is responsible for managing the lifecycle of a transport instance, including its initialization,
|
||||
* state transitions, message transmission, and graceful shutdown. It provides a framework for implementing
|
||||
* specific transport mechanisms by defining abstract methods that subclasses must implement.
|
||||
*
|
||||
* Thread-safety is achieved through the use of atomic references to manage transport state transitions and
|
||||
* to ensure invariants during lifecycle events. The initialization and shutdown logic is designed to handle
|
||||
* async workflows, ensuring proper resource cleanup in the case of failure or cancellation.
|
||||
*/
|
||||
@OptIn(ExperimentalAtomicApi::class, InternalMcpApi::class)
|
||||
public abstract class AbstractClientTransport : AbstractTransport() {
|
||||
|
||||
protected abstract val logger: KLogger
|
||||
|
||||
/**
|
||||
* Represents the current state of the client transport in an atomic and thread-safe manner.
|
||||
*
|
||||
* This private field is used internally to manage state transitions of the transport, ensuring
|
||||
* consistency across concurrent operations. The state transitions are validated and managed
|
||||
* using the `stateTransition` method, adhering to defined rules in [ClientTransportState.VALID_TRANSITIONS].
|
||||
*
|
||||
* @see ClientTransportState
|
||||
* @see stateTransition
|
||||
* @see checkState
|
||||
*/
|
||||
private val _state: AtomicReference<ClientTransportState> = AtomicReference(ClientTransportState.New)
|
||||
|
||||
/**
|
||||
* Current transport state. Thread-safe via atomic reference.
|
||||
* Initial state is [ClientTransportState.New].
|
||||
*/
|
||||
@InternalMcpApi
|
||||
protected val state: ClientTransportState
|
||||
get() = _state.load()
|
||||
|
||||
/**
|
||||
* Updates the internal state of the client transport to the specified new state.
|
||||
*
|
||||
* This method is used to manage the lifecycle and operational state of the client transport
|
||||
* by transitioning it to the provided [new] state. The new state is stored atomically,
|
||||
* ensuring thread safety during concurrent modifications.
|
||||
*
|
||||
* @param new The new state to transition the client transport to. It must be a valid state
|
||||
* as defined in the transport's lifecycle logic.
|
||||
*/
|
||||
@InternalMcpApi
|
||||
protected fun updateState(new: ClientTransportState) {
|
||||
_state.store(new)
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs transport-specific initialization (connections, I/O streams, background coroutines).
|
||||
*
|
||||
* Called by [start] during [ClientTransportState.Initializing]. On exception, state transitions to
|
||||
* [ClientTransportState.InitializationFailed], [closeResources] is called, and exception propagates.
|
||||
*/
|
||||
protected abstract suspend fun initialize()
|
||||
|
||||
/**
|
||||
* Atomically transitions state from `from` to `to`.
|
||||
*
|
||||
* Validates transition per [ClientTransportState.VALID_TRANSITIONS] and performs atomic compare-and-exchange.
|
||||
*
|
||||
* @throws IllegalArgumentException if transition isn't allowed
|
||||
* @throws IllegalStateException if the actual state doesn't match `from`
|
||||
*/
|
||||
@InternalMcpApi
|
||||
protected fun stateTransition(from: ClientTransportState, to: ClientTransportState) {
|
||||
require(to in ClientTransportState.VALID_TRANSITIONS.getValue(from)) {
|
||||
"Invalid transition: $from → $to"
|
||||
}
|
||||
val actualState = _state.compareAndExchange(
|
||||
expectedValue = from,
|
||||
newValue = to,
|
||||
)
|
||||
check(actualState == from) {
|
||||
"Can't change state: expected transport state $from, but found $actualState."
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies that the current transport state matches the expected state and throws an exception if it does not.
|
||||
*
|
||||
* This method ensures that the transport's state is in alignment with the caller’s expectations before
|
||||
* proceeding with further operations. It is often used to enforce state invariants within the transport's
|
||||
* lifecycle mechanics, enabling robust error handling and debugging in case of unexpected state transitions.
|
||||
*
|
||||
* @param expected The expected transport state. An exception will be thrown if the actual state does not match this value.
|
||||
* @throws IllegalStateException If the current state does not match the expected state.
|
||||
*/
|
||||
protected fun checkState(
|
||||
expected: ClientTransportState,
|
||||
lazyMessage: (ClientTransportState) -> Any = {
|
||||
"Expected transport state $expected, but found $it"
|
||||
},
|
||||
) {
|
||||
val actualState = state
|
||||
check(actualState == expected) { lazyMessage }
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates the transport by transitioning through the required states to prepare it for operation.
|
||||
*
|
||||
* This method transitions the transport state from `New` to `Initializing`, performs initialization
|
||||
* logic specific to the transport implementation, and then transitions the state to `Operational`
|
||||
* upon successful initialization. If an exception occurs during initialization, the state is transitioned
|
||||
* to `InitializationFailed`, resources are cleaned up, and the exception is rethrown.
|
||||
*
|
||||
* This method operates within a suspend context to allow for asynchronous initialization tasks.
|
||||
*
|
||||
* **Important! This method will eventually become `final`.
|
||||
* Please don't override it, or consistency guarantees might be lost. Override [initialize] instead.**
|
||||
*
|
||||
* @throws Exception if the initialization process fails and transfers state
|
||||
* to [ClientTransportState.InitializationFailed].
|
||||
* @see initialize
|
||||
*/
|
||||
public override suspend fun start() {
|
||||
stateTransition(from = ClientTransportState.New, to = ClientTransportState.Initializing)
|
||||
try {
|
||||
initialize()
|
||||
stateTransition(from = ClientTransportState.Initializing, to = ClientTransportState.Operational)
|
||||
} catch (e: Exception) {
|
||||
_state.store(ClientTransportState.InitializationFailed)
|
||||
closeResources()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a JSON-RPC message using the transport layer.
|
||||
*
|
||||
* This method ensures that the transport is operational before attempting to send the message.
|
||||
* If the transport's state does not allow sending operations, an exception is thrown.
|
||||
* It delegates the actual transmission to the abstract [performSend] method, which must be
|
||||
* implemented by subclasses to handle the specifics of the transmission mechanism. Errors
|
||||
* during the send operation are handled appropriately, and cancellation exceptions are always
|
||||
* propagated.
|
||||
*
|
||||
* **Important! This method will eventually become `final`.
|
||||
* Please don't override it, or consistency guarantees might be lost. Override [performSend] instead.**
|
||||
*
|
||||
* @param message The JSON-RPC message to be sent. Must adhere to the JSON-RPC 2.0 specification.
|
||||
* @param options Optional parameters that influence how the message is transmitted, such as
|
||||
* timeout specifications or message delivery guarantees. Can be null if no
|
||||
* specific options are required.
|
||||
* @throws McpException If the transport is not operational or other application-specific errors occur.
|
||||
* @throws CancellationException If the coroutine is canceled.
|
||||
* @see performSend
|
||||
*/
|
||||
public override suspend fun send(message: JSONRPCMessage, options: TransportSendOptions?) {
|
||||
// fast path - state check to avoid nonsense operations
|
||||
if (state != ClientTransportState.Operational) {
|
||||
throw McpException(
|
||||
code = CONNECTION_CLOSED,
|
||||
message = "Transport is not ready",
|
||||
)
|
||||
}
|
||||
// limitation: state could still change at the time of use
|
||||
try {
|
||||
performSend(message, options)
|
||||
} catch (e: CancellationException) {
|
||||
throw e // Always propagate cancellation
|
||||
} catch (e: Exception) {
|
||||
_onError(e)
|
||||
if (e is McpException) {
|
||||
throw e
|
||||
} else {
|
||||
throw McpException(
|
||||
code = INTERNAL_ERROR,
|
||||
message = "Error while sending message: ${e.message}",
|
||||
cause = e,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transmits a JSON-RPC message via the underlying protocol.
|
||||
*
|
||||
* The method is responsible for transmitting a given JSON-RPC message to the intended destination.
|
||||
* It is implemented by concrete subclasses of the transport to handle specific transmission
|
||||
* mechanisms.
|
||||
*
|
||||
* Called by [send] after verifying transport [state].
|
||||
*
|
||||
* @param message The JSON-RPC message to be sent. Must comply with the JSON-RPC 2.0 specification.
|
||||
* @param options Optional parameters that influence how the message is transmitted, such as
|
||||
* timeout settings or delivery guarantees. May be null if no specific options
|
||||
* are required.
|
||||
* @see send
|
||||
*/
|
||||
protected abstract suspend fun performSend(message: JSONRPCMessage, options: TransportSendOptions? = null)
|
||||
|
||||
/**
|
||||
* Closes the client transport gracefully, transitioning its state to a non-operational state.
|
||||
*
|
||||
* **Important! This method will eventually become `final`.
|
||||
* Please don't override it, or consistency guarantees might be lost.**
|
||||
*
|
||||
* The method is designed to operate within a suspendable context, allowing support for asynchronous
|
||||
* behavior during the resource cleanup and state transitions.
|
||||
*
|
||||
* Transitions [ClientTransportState.Operational] → [ClientTransportState.ShuttingDown] → [ClientTransportState.Stopped].
|
||||
* Calls [closeResources] then invokes [_onClose] callbacks exactly once.
|
||||
* On [kotlin.coroutines.cancellation.CancellationException], transitions to [ClientTransportState.ShutdownFailed] and propagates.
|
||||
*
|
||||
* The method also handles unexpected exceptions gracefully during resource cleanup by transitioning
|
||||
* the transport to the `ShutdownFailed` state.
|
||||
*
|
||||
* **Important! This method will eventually become `final`.
|
||||
* Please don't override it, or consistency guarantees might be lost. Override [closeResources] instead.**
|
||||
*
|
||||
* @see closeResources
|
||||
*/
|
||||
public override suspend fun close() {
|
||||
val performClose: Boolean
|
||||
when (state) {
|
||||
ClientTransportState.Operational -> {
|
||||
// Only Operational state can transition to ShuttingDown
|
||||
stateTransition(ClientTransportState.Operational, ClientTransportState.ShuttingDown)
|
||||
performClose = true
|
||||
}
|
||||
|
||||
ClientTransportState.New -> {
|
||||
// New state transitions directly to Stopped without any cleanup
|
||||
stateTransition(ClientTransportState.New, ClientTransportState.Stopped)
|
||||
performClose = false
|
||||
}
|
||||
|
||||
else -> {
|
||||
// Already shutting down or in terminal state - idempotent, do nothing
|
||||
performClose = false
|
||||
}
|
||||
}
|
||||
if (performClose) {
|
||||
try {
|
||||
closeResources()
|
||||
stateTransition(from = ClientTransportState.ShuttingDown, to = ClientTransportState.Stopped)
|
||||
} catch (e: CancellationException) {
|
||||
stateTransition(from = ClientTransportState.ShuttingDown, to = ClientTransportState.ShutdownFailed)
|
||||
throw e // Always propagate cancellation
|
||||
} catch (e: Exception) {
|
||||
// Ignore errors during cleanup
|
||||
logger.error(e) { "Error during transport shutdown" }
|
||||
stateTransition(from = ClientTransportState.ShuttingDown, to = ClientTransportState.ShutdownFailed)
|
||||
} finally {
|
||||
invokeOnCloseCallback()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases transport-specific resources (coroutines, connections, streams).
|
||||
*
|
||||
* Called by [close] during [ClientTransportState.ShuttingDown].
|
||||
* May be called even if [initialize] failed partially.
|
||||
*/
|
||||
protected abstract suspend fun closeResources()
|
||||
}
|
||||
|
|
@ -2,15 +2,18 @@ package io.modelcontextprotocol.kotlin.sdk.shared
|
|||
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlin.concurrent.atomics.AtomicBoolean
|
||||
import kotlin.concurrent.atomics.ExperimentalAtomicApi
|
||||
|
||||
/**
|
||||
* Implements [onClose], [onError] and [onMessage] functions of [Transport] providing
|
||||
* corresponding [_onClose], [_onError] and [_onMessage] properties to use for an implementation.
|
||||
*/
|
||||
@OptIn(ExperimentalAtomicApi::class)
|
||||
@Suppress("PropertyName")
|
||||
public abstract class AbstractTransport : Transport {
|
||||
protected var _onClose: (() -> Unit) = {}
|
||||
private set
|
||||
private val onCloseCalled = AtomicBoolean(false)
|
||||
private var _onClose: (() -> Unit) = {}
|
||||
protected var _onError: ((Throwable) -> Unit) = {}
|
||||
private set
|
||||
|
||||
|
|
@ -51,4 +54,18 @@ public abstract class AbstractTransport : Transport {
|
|||
|
||||
_onMessageInitialized.complete(Unit)
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the `_onClose` callback if it has not been already triggered.
|
||||
*
|
||||
* This method ensures the `_onClose` callback is executed only once by utilizing
|
||||
* an atomic flag (`onCloseCalled`). If the callback has already been executed,
|
||||
* the method does nothing. Any exceptions thrown during the execution of the
|
||||
* `_onClose` callback are caught and suppressed.
|
||||
*/
|
||||
protected fun invokeOnCloseCallback() {
|
||||
if (onCloseCalled.compareAndSet(expectedValue = false, newValue = true)) {
|
||||
runCatching { _onClose() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,79 @@
|
|||
package io.modelcontextprotocol.kotlin.sdk.shared
|
||||
|
||||
/**
|
||||
* States of a client transport within the protocol lifecycle
|
||||
*
|
||||
* These states are generally aligned with the corresponding phases
|
||||
* defined under the MCP [Protocol Lifecycle](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle).
|
||||
*/
|
||||
public enum class ClientTransportState {
|
||||
|
||||
/**
|
||||
* The transport has just been created.
|
||||
*
|
||||
* This is the Initial state
|
||||
*/
|
||||
New,
|
||||
|
||||
/**
|
||||
* Indicates that the protocol
|
||||
* is in the [Initialization Phase](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#initialization).
|
||||
*/
|
||||
Initializing,
|
||||
|
||||
/**
|
||||
* Indicates that the initialization phase of the protocol lifecycle has failed.
|
||||
*
|
||||
* This state suggests that the transport encountered an error or issue during
|
||||
* initialization, preventing it from successfully transitioning to a fully operational state.
|
||||
*/
|
||||
InitializationFailed,
|
||||
|
||||
/**
|
||||
* Represents the [operational phase](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#operation)
|
||||
* of the protocol lifecycle.
|
||||
*
|
||||
* During the operation phase, the client and server exchange messages according to the negotiated capabilities.
|
||||
*/
|
||||
Operational,
|
||||
|
||||
/**
|
||||
* Represents the shutting down phase of the protocol lifecycle.
|
||||
*
|
||||
* This state indicates that the transport is in the process of shutting down
|
||||
* and transitioning to a non-operational state.
|
||||
*
|
||||
* During this phase, no new outgoing messages should be accepted.
|
||||
*/
|
||||
ShuttingDown,
|
||||
|
||||
/**
|
||||
* Indicates that the shutdown phase of the protocol lifecycle has failed.
|
||||
*
|
||||
* This state signifies that an error was encountered during the shutdown phase.
|
||||
*/
|
||||
ShutdownFailed,
|
||||
|
||||
/**
|
||||
* Indicates that the transport has fully stopped.
|
||||
*
|
||||
* This state represents the final phase of the lifecycle, where the transport is no longer
|
||||
* operational and all cleanup routines or resource deallocations have been completed.
|
||||
*/
|
||||
Stopped,
|
||||
|
||||
;
|
||||
|
||||
internal companion object {
|
||||
val VALID_TRANSITIONS: Map<ClientTransportState, Set<ClientTransportState>> = mapOf(
|
||||
New to setOf(Initializing, Stopped),
|
||||
Initializing to setOf(Operational, InitializationFailed),
|
||||
Operational to setOf(ShuttingDown),
|
||||
ShuttingDown to setOf(Stopped, ShutdownFailed),
|
||||
// Terminal states allow no transitions
|
||||
InitializationFailed to emptySet(),
|
||||
Stopped to emptySet(),
|
||||
ShutdownFailed to emptySet(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -255,7 +255,7 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
|
|||
}
|
||||
|
||||
logger.info { "Starting transport" }
|
||||
return transport.start()
|
||||
transport.start()
|
||||
}
|
||||
|
||||
private fun doClose() {
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ public interface Transport {
|
|||
*
|
||||
* This method should only be called after callbacks are installed, or else messages may be lost.
|
||||
*
|
||||
* Method waits for the initialization flow to complete and then returns, so the transport is ready to send and receive user messages.
|
||||
*
|
||||
* NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes,
|
||||
* as they will implicitly call start().
|
||||
*/
|
||||
|
|
@ -26,7 +28,7 @@ public interface Transport {
|
|||
public suspend fun send(message: JSONRPCMessage, options: TransportSendOptions? = null)
|
||||
|
||||
/**
|
||||
* Closes the connection.
|
||||
* Closes the transport.
|
||||
*/
|
||||
public suspend fun close()
|
||||
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ public abstract class WebSocketMcpTransport : AbstractTransport() {
|
|||
if (it != null) {
|
||||
_onError.invoke(it)
|
||||
} else {
|
||||
_onClose.invoke()
|
||||
invokeOnCloseCallback()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,498 @@
|
|||
package io.modelcontextprotocol.kotlin.sdk.shared
|
||||
|
||||
import io.github.oshai.kotlinlogging.KLogger
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import io.kotest.assertions.throwables.shouldThrow
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.kotest.matchers.string.shouldContain
|
||||
import io.mockk.spyk
|
||||
import io.modelcontextprotocol.kotlin.sdk.InternalMcpApi
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.McpException
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.PingRequest
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.RPCError
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.toJSON
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.api.Nested
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.CsvSource
|
||||
import org.junit.jupiter.params.provider.EnumSource
|
||||
import org.junit.jupiter.params.provider.MethodSource
|
||||
import kotlin.concurrent.atomics.ExperimentalAtomicApi
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
|
||||
/**
|
||||
* Unit tests for [AbstractClientTransport] state machine and lifecycle.
|
||||
*
|
||||
* Tests behavioral correctness of state transitions, lifecycle management,
|
||||
* and message sending without relying on mocking frameworks.
|
||||
*/
|
||||
@OptIn(ExperimentalAtomicApi::class)
|
||||
class AbstractClientTransportTest {
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun nonMcpExceptions() = listOf(
|
||||
TestException("Generic failure"),
|
||||
java.io.IOException("Network error"),
|
||||
IllegalStateException("Invalid state"),
|
||||
)
|
||||
}
|
||||
|
||||
private lateinit var transport: TestClientTransport
|
||||
|
||||
@BeforeEach
|
||||
fun beforeEach() {
|
||||
transport = spyk(TestClientTransport())
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Lifecycle")
|
||||
inner class LifecycleTests {
|
||||
|
||||
@Test
|
||||
fun `should start with NEW state`() {
|
||||
transport.currentState shouldBe ClientTransportState.New
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should transition to OPERATIONAL after successful start`() = runTest {
|
||||
transport.start()
|
||||
|
||||
transport.currentState shouldBe ClientTransportState.Operational
|
||||
transport.initializeCalled shouldBe true
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should call initialize during start`() = runTest {
|
||||
transport.start()
|
||||
|
||||
transport.initializeCalled shouldBe true
|
||||
transport.currentState shouldBe ClientTransportState.Operational
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should transition to INITIALIZATION_FAILED on start error`() = runTest {
|
||||
transport.shouldFailInitialization = true
|
||||
|
||||
shouldThrow<TestException> {
|
||||
transport.start()
|
||||
}
|
||||
|
||||
transport.currentState shouldBe ClientTransportState.InitializationFailed
|
||||
transport.closeResourcesCalled shouldBe true
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should call closeResources on initialization failure`() = runTest {
|
||||
transport.shouldFailInitialization = true
|
||||
|
||||
shouldThrow<TestException> {
|
||||
transport.start()
|
||||
}
|
||||
|
||||
transport.closeResourcesCalled shouldBe true
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should reject starting twice`() = runTest {
|
||||
transport.start()
|
||||
|
||||
val exception = shouldThrow<IllegalStateException> {
|
||||
transport.start()
|
||||
}
|
||||
exception.message shouldContain "expected transport state New"
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should transition to STOPPED after successful close`() = runTest {
|
||||
transport.start()
|
||||
transport.close()
|
||||
|
||||
transport.currentState shouldBe ClientTransportState.Stopped
|
||||
transport.closeResourcesCalled shouldBe true
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should call closeResources during close`() = runTest {
|
||||
transport.start()
|
||||
|
||||
transport.close()
|
||||
|
||||
transport.closeResourcesCalled shouldBe true
|
||||
transport.currentState shouldBe ClientTransportState.Stopped
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should be idempotent when closed multiple times`() = runTest {
|
||||
// given
|
||||
transport.start()
|
||||
transport.close()
|
||||
// when
|
||||
transport.close()
|
||||
transport.close()
|
||||
|
||||
transport.currentState shouldBe ClientTransportState.Stopped
|
||||
transport.closeResourcesCallCount shouldBe 1
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should call onClose callback exactly once on multiple close calls`() = runTest {
|
||||
var onCloseCallCount = 0
|
||||
transport.onClose { onCloseCallCount++ }
|
||||
|
||||
transport.start()
|
||||
transport.close()
|
||||
transport.close()
|
||||
|
||||
onCloseCallCount shouldBe 1
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should transition to SHUTDOWN_FAILED on close error`() = runTest {
|
||||
transport.shouldFailClose = true
|
||||
transport.start()
|
||||
|
||||
transport.close()
|
||||
|
||||
transport.currentState shouldBe ClientTransportState.ShutdownFailed
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should call onClose even when close fails`() = runTest {
|
||||
// given
|
||||
var onCloseCalled = false
|
||||
transport.onClose { onCloseCalled = true }
|
||||
transport.shouldFailClose = true
|
||||
transport.start()
|
||||
// when
|
||||
transport.close()
|
||||
// then
|
||||
onCloseCalled shouldBe true
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should propagate CancellationException on close`() = runTest {
|
||||
// given
|
||||
transport.shouldThrowCancellation = true
|
||||
transport.start()
|
||||
// when-then
|
||||
shouldThrow<CancellationException> {
|
||||
transport.close()
|
||||
}
|
||||
|
||||
transport.currentState shouldBe ClientTransportState.ShutdownFailed
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should call onClose even when CancellationException is thrown`() = runTest {
|
||||
var onCloseCalled = false
|
||||
transport.onClose { onCloseCalled = true }
|
||||
transport.shouldThrowCancellation = true
|
||||
transport.start()
|
||||
|
||||
shouldThrow<CancellationException> {
|
||||
transport.close()
|
||||
}
|
||||
|
||||
onCloseCalled shouldBe true
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("State Transitions")
|
||||
inner class StateTransitionTests {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(
|
||||
"New, Initializing",
|
||||
"New, Stopped",
|
||||
"Initializing, Operational",
|
||||
"Initializing, InitializationFailed",
|
||||
"Operational, ShuttingDown",
|
||||
"ShuttingDown, Stopped",
|
||||
"ShuttingDown, ShutdownFailed",
|
||||
)
|
||||
fun `should allow valid transitions`(fromName: String, toName: String) {
|
||||
val from = ClientTransportState.valueOf(fromName)
|
||||
val to = ClientTransportState.valueOf(toName)
|
||||
|
||||
transport.forceState(from)
|
||||
transport.testStateTransition(from, to)
|
||||
|
||||
transport.currentState shouldBe to
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(
|
||||
// From New: only Initializing is valid
|
||||
"New, Operational",
|
||||
"New, InitializationFailed",
|
||||
"New, ShuttingDown",
|
||||
"New, ShutdownFailed",
|
||||
// From Initializing: only Operational or InitializationFailed are valid
|
||||
"Initializing, New",
|
||||
"Initializing, Initializing",
|
||||
"Initializing, ShuttingDown",
|
||||
"Initializing, Stopped",
|
||||
"Initializing, ShutdownFailed",
|
||||
// From Operational: only ShuttingDown is valid
|
||||
"Operational, New",
|
||||
"Operational, Initializing",
|
||||
"Operational, InitializationFailed",
|
||||
"Operational, Operational",
|
||||
"Operational, Stopped",
|
||||
"Operational, ShutdownFailed",
|
||||
// From ShuttingDown: only Stopped or ShutdownFailed are valid
|
||||
"ShuttingDown, New",
|
||||
"ShuttingDown, Initializing",
|
||||
"ShuttingDown, InitializationFailed",
|
||||
"ShuttingDown, Operational",
|
||||
"ShuttingDown, ShuttingDown",
|
||||
// From terminal states: no transitions allowed
|
||||
"InitializationFailed, New",
|
||||
"InitializationFailed, Operational",
|
||||
"Stopped, New",
|
||||
"Stopped, Operational",
|
||||
"ShutdownFailed, New",
|
||||
"ShutdownFailed, Operational",
|
||||
)
|
||||
fun `should reject invalid transitions`(fromName: String, toName: String) {
|
||||
val from = ClientTransportState.valueOf(fromName)
|
||||
val to = ClientTransportState.valueOf(toName)
|
||||
|
||||
transport.forceState(from)
|
||||
|
||||
val exception = shouldThrow<IllegalArgumentException> {
|
||||
transport.testStateTransition(from, to)
|
||||
}
|
||||
exception.message shouldContain "Invalid transition: $from → $to"
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Send Operations")
|
||||
inner class SendTests {
|
||||
|
||||
@Test
|
||||
fun `should send message successfully when OPERATIONAL`() = runTest {
|
||||
val message = PingRequest().toJSON()
|
||||
|
||||
transport.start()
|
||||
transport.send(message)
|
||||
|
||||
transport.sentMessages shouldBe listOf(message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should pass options to performSend`() = runTest {
|
||||
val message = PingRequest().toJSON()
|
||||
val options = TransportSendOptions()
|
||||
|
||||
transport.start()
|
||||
transport.send(message, options)
|
||||
|
||||
transport.sentMessages shouldBe listOf(message)
|
||||
transport.lastSendOptions shouldBe options
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should throw when sending before start`() = runTest {
|
||||
val exception = shouldThrow<McpException> {
|
||||
transport.send(PingRequest().toJSON())
|
||||
}
|
||||
|
||||
exception.code shouldBe RPCError.ErrorCode.CONNECTION_CLOSED
|
||||
exception.message shouldContain "Transport is not ready"
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should throw when sending after close`() = runTest {
|
||||
transport.start()
|
||||
transport.close()
|
||||
|
||||
val exception = shouldThrow<McpException> {
|
||||
transport.send(PingRequest().toJSON())
|
||||
}
|
||||
|
||||
exception.code shouldBe RPCError.ErrorCode.CONNECTION_CLOSED
|
||||
exception.message shouldContain "Transport is not ready"
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(
|
||||
value = ClientTransportState::class,
|
||||
names = ["Operational"],
|
||||
mode = EnumSource.Mode.EXCLUDE,
|
||||
)
|
||||
fun `should throw when sending in non-OPERATIONAL state`(state: ClientTransportState) = runTest {
|
||||
transport.forceState(state)
|
||||
|
||||
val exception = shouldThrow<McpException> {
|
||||
transport.send(PingRequest().toJSON())
|
||||
}
|
||||
|
||||
exception.code shouldBe RPCError.ErrorCode.CONNECTION_CLOSED
|
||||
exception.message shouldContain "Transport is not ready"
|
||||
transport.sentMessages.isEmpty() shouldBe true
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should call onError when performSend throws McpException`() = runTest {
|
||||
var errorCallCount = 0
|
||||
var capturedError: Throwable? = null
|
||||
transport.onError { error ->
|
||||
errorCallCount++
|
||||
capturedError = error
|
||||
}
|
||||
transport.shouldFailSend = true
|
||||
transport.sendException = McpException(RPCError.ErrorCode.INTERNAL_ERROR, "Send failed")
|
||||
|
||||
transport.start()
|
||||
val exception = shouldThrow<McpException> {
|
||||
transport.send(PingRequest().toJSON())
|
||||
}
|
||||
|
||||
errorCallCount shouldBe 1
|
||||
capturedError shouldBe transport.sendException
|
||||
exception shouldBe transport.sendException
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("io.modelcontextprotocol.kotlin.sdk.shared.AbstractClientTransportTest#nonMcpExceptions")
|
||||
fun `should call onError when performSend throws non-MCP exception`(testException: Throwable) = runTest {
|
||||
var errorCallCount = 0
|
||||
var capturedError: Throwable? = null
|
||||
transport.onError { error ->
|
||||
errorCallCount++
|
||||
capturedError = error
|
||||
}
|
||||
transport.shouldFailSend = true
|
||||
transport.sendException = testException
|
||||
|
||||
transport.start()
|
||||
val exception = shouldThrow<McpException> {
|
||||
transport.send(PingRequest().toJSON())
|
||||
}
|
||||
|
||||
errorCallCount shouldBe 1
|
||||
capturedError shouldBe testException
|
||||
exception.code shouldBe RPCError.ErrorCode.INTERNAL_ERROR
|
||||
exception.cause shouldBe testException
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should NOT call onError when performSend throws CancellationException`() = runTest {
|
||||
var errorCallCount = 0
|
||||
transport.onError { errorCallCount++ }
|
||||
transport.shouldFailSend = true
|
||||
transport.sendException = CancellationException("Operation cancelled")
|
||||
|
||||
transport.start()
|
||||
shouldThrow<CancellationException> {
|
||||
transport.send(PingRequest().toJSON())
|
||||
}
|
||||
|
||||
errorCallCount shouldBe 0
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Idempotency")
|
||||
inner class IdempotencyTests {
|
||||
|
||||
@Test
|
||||
fun `should be idempotent when closing from NEW state`() = runTest {
|
||||
transport.close()
|
||||
|
||||
transport.currentState shouldBe ClientTransportState.Stopped
|
||||
transport.closeResourcesCalled shouldBe false
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should be idempotent when closing from INITIALIZATION_FAILED state`() = runTest {
|
||||
transport.shouldFailInitialization = true
|
||||
shouldThrow<TestException> { transport.start() }
|
||||
|
||||
transport.close()
|
||||
|
||||
transport.currentState shouldBe ClientTransportState.InitializationFailed
|
||||
// closeResources was called during a failed start, but not during this close
|
||||
transport.closeResourcesCallCount shouldBe 1
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(
|
||||
value = ClientTransportState::class,
|
||||
names = ["ShuttingDown", "ShutdownFailed", "Stopped"],
|
||||
)
|
||||
fun `should be idempotent when closing from terminal or shutdown states`(state: ClientTransportState) =
|
||||
runTest {
|
||||
transport.forceState(state)
|
||||
val initialCloseCount = transport.closeResourcesCallCount
|
||||
|
||||
transport.close()
|
||||
|
||||
transport.currentState shouldBe state
|
||||
transport.closeResourcesCallCount shouldBe initialCloseCount
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple test implementation of [AbstractClientTransport] for behavioral testing.
|
||||
* Tracks method calls without mocking frameworks.
|
||||
*/
|
||||
@OptIn(InternalMcpApi::class)
|
||||
private class TestClientTransport : AbstractClientTransport() {
|
||||
override val logger: KLogger = KotlinLogging.logger {}
|
||||
val sentMessages = mutableListOf<JSONRPCMessage>()
|
||||
var lastSendOptions: TransportSendOptions? = null
|
||||
var initializeCalled = false
|
||||
var closeResourcesCalled = false
|
||||
var closeResourcesCallCount = 0
|
||||
var shouldFailInitialization = false
|
||||
var shouldFailClose = false
|
||||
var shouldThrowCancellation = false
|
||||
var shouldFailSend = false
|
||||
var sendException: Throwable? = null
|
||||
|
||||
val currentState: ClientTransportState
|
||||
get() = state
|
||||
|
||||
override suspend fun initialize() {
|
||||
initializeCalled = true
|
||||
if (shouldFailInitialization) {
|
||||
throw TestException("Initialization failed")
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun performSend(message: JSONRPCMessage, options: TransportSendOptions?) {
|
||||
if (shouldFailSend) {
|
||||
throw sendException ?: TestException("Send failed")
|
||||
}
|
||||
sentMessages.add(message)
|
||||
lastSendOptions = options
|
||||
}
|
||||
|
||||
override suspend fun closeResources() {
|
||||
closeResourcesCalled = true
|
||||
closeResourcesCallCount++
|
||||
|
||||
when {
|
||||
shouldThrowCancellation -> throw CancellationException("Test cancellation")
|
||||
shouldFailClose -> throw TestException("Close failed")
|
||||
}
|
||||
}
|
||||
|
||||
fun testStateTransition(from: ClientTransportState, to: ClientTransportState) {
|
||||
stateTransition(from, to)
|
||||
}
|
||||
|
||||
fun forceState(newState: ClientTransportState) = updateState(newState)
|
||||
}
|
||||
|
||||
private class TestException(message: String) : Exception(message)
|
||||
}
|
||||
Loading…
Reference in a new issue