Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,6 @@ class ProtocolConcurrencyIntegrationTest {
),
)

// ChannelTransport delivers inbound messages as soon as its read loop starts, which is before
// start() marks it operational. Creating the session first keeps the client's initialize from
// landing on a transport that would reject the session's response.
private suspend fun connect(
client: Client,
clientTransport: ChannelTransport,
Expand Down
1 change: 1 addition & 0 deletions kotlin-sdk-core/api/kotlin-sdk-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public abstract class io/modelcontextprotocol/kotlin/sdk/shared/AbstractClientTr
protected abstract fun getLogger ()Lio/github/oshai/kotlinlogging/KLogger;
protected final fun getState ()Lio/modelcontextprotocol/kotlin/sdk/shared/ClientTransportState;
protected abstract fun initialize (Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun onMessage (Lkotlin/jvm/functions/Function2;)V
protected abstract fun performSend (Lio/modelcontextprotocol/kotlin/sdk/types/JSONRPCMessage;Lio/modelcontextprotocol/kotlin/sdk/shared/TransportSendOptions;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public static synthetic fun performSend$default (Lio/modelcontextprotocol/kotlin/sdk/shared/AbstractClientTransport;Lio/modelcontextprotocol/kotlin/sdk/types/JSONRPCMessage;Lio/modelcontextprotocol/kotlin/sdk/shared/TransportSendOptions;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object;
public fun send (Lio/modelcontextprotocol/kotlin/sdk/types/JSONRPCMessage;Lio/modelcontextprotocol/kotlin/sdk/shared/TransportSendOptions;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
Expand Down
1 change: 1 addition & 0 deletions kotlin-sdk-core/api/kotlin-sdk-core.klib.api
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,7 @@ abstract class io.modelcontextprotocol.kotlin.sdk.shared/AbstractClientTransport
final fun checkState(io.modelcontextprotocol.kotlin.sdk.shared/ClientTransportState, kotlin/Function1<io.modelcontextprotocol.kotlin.sdk.shared/ClientTransportState, kotlin/Any> = ...) // io.modelcontextprotocol.kotlin.sdk.shared/AbstractClientTransport.checkState|checkState(io.modelcontextprotocol.kotlin.sdk.shared.ClientTransportState;kotlin.Function1<io.modelcontextprotocol.kotlin.sdk.shared.ClientTransportState,kotlin.Any>){}[0]
final fun stateTransition(io.modelcontextprotocol.kotlin.sdk.shared/ClientTransportState, io.modelcontextprotocol.kotlin.sdk.shared/ClientTransportState) // io.modelcontextprotocol.kotlin.sdk.shared/AbstractClientTransport.stateTransition|stateTransition(io.modelcontextprotocol.kotlin.sdk.shared.ClientTransportState;io.modelcontextprotocol.kotlin.sdk.shared.ClientTransportState){}[0]
final fun updateState(io.modelcontextprotocol.kotlin.sdk.shared/ClientTransportState) // io.modelcontextprotocol.kotlin.sdk.shared/AbstractClientTransport.updateState|updateState(io.modelcontextprotocol.kotlin.sdk.shared.ClientTransportState){}[0]
open fun onMessage(kotlin.coroutines/SuspendFunction1<io.modelcontextprotocol.kotlin.sdk.types/JSONRPCMessage, kotlin/Unit>) // io.modelcontextprotocol.kotlin.sdk.shared/AbstractClientTransport.onMessage|onMessage(kotlin.coroutines.SuspendFunction1<io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage,kotlin.Unit>){}[0]
open suspend fun close() // io.modelcontextprotocol.kotlin.sdk.shared/AbstractClientTransport.close|close(){}[0]
open suspend fun send(io.modelcontextprotocol.kotlin.sdk.types/JSONRPCMessage, io.modelcontextprotocol.kotlin.sdk.shared/TransportSendOptions?) // io.modelcontextprotocol.kotlin.sdk.shared/AbstractClientTransport.send|send(io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage;io.modelcontextprotocol.kotlin.sdk.shared.TransportSendOptions?){}[0]
open suspend fun start() // io.modelcontextprotocol.kotlin.sdk.shared/AbstractClientTransport.start|start(){}[0]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ 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 kotlinx.coroutines.CompletableDeferred
import kotlin.concurrent.atomics.AtomicReference
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.coroutines.cancellation.CancellationException
Expand Down Expand Up @@ -39,6 +40,8 @@ public abstract class AbstractClientTransport : AbstractTransport() {
*/
private val _state: AtomicReference<ClientTransportState> = AtomicReference(ClientTransportState.New)

private val operational = CompletableDeferred<Unit>()

/**
* Current transport state. Thread-safe via atomic reference.
* Initial state is [ClientTransportState.New].
Expand Down Expand Up @@ -136,13 +139,25 @@ public abstract class AbstractClientTransport : AbstractTransport() {
try {
initialize()
stateTransition(from = ClientTransportState.Initializing, to = ClientTransportState.Operational)
operational.complete(Unit)
} catch (e: Exception) {
_state.store(ClientTransportState.InitializationFailed)
closeResources()
throw e
}
}

/**
* Registers [block] to handle inbound messages. Messages received before [start] completes
* are handed to [block] only once the transport is [ClientTransportState.Operational].
*/
public override fun onMessage(block: suspend (JSONRPCMessage) -> Unit) {
super.onMessage { message ->
operational.await()
block(message)
}
}

/**
* Sends a JSON-RPC message using the transport layer.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@ import io.kotest.matchers.string.shouldContain
import io.kotest.matchers.types.shouldBeSameInstanceAs
import io.modelcontextprotocol.kotlin.sdk.InternalMcpApi
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCResponse
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.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
Expand Down Expand Up @@ -136,6 +140,18 @@ class AbstractClientTransportTest {
transport.lastSendOptions shouldBeSameInstanceAs options
}

@Test
fun `should answer a message received during initialization once OPERATIONAL`() = runTest {
val request = PingRequest().toJSON()
val response = JSONRPCResponse(request.id)
transport.onMessage { transport.send(response) }
transport.receiveDuringInitialize = request

transport.start()

transport.sentMessages shouldBe listOf(response)
}

@Test
fun `should throw when sending before start`() = runTest {
assertSendRejected()
Expand Down Expand Up @@ -218,13 +234,23 @@ class AbstractClientTransportTest {
var initializeFailure: Exception? = null
var closeFailure: Exception? = null
var sendFailure: Exception? = null
var receiveDuringInitialize: JSONRPCMessage? = null

val currentState: ClientTransportState
get() = state

override suspend fun initialize() {
initializeCalled = true
initializeFailure?.let { throw it }
receiveDuringInitialize?.let { message ->
CoroutineScope(UnconfinedTestDispatcher()).launch {
try {
_onMessage(message)
} catch (e: McpException) {
_onError(e)
}
}
}
}

override suspend fun performSend(message: JSONRPCMessage, options: TransportSendOptions?) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,15 @@ import io.kotest.matchers.shouldBe
import io.modelcontextprotocol.kotlin.sdk.ExperimentalMcpApi
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCRequest
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCResponse
import io.modelcontextprotocol.kotlin.sdk.types.RequestId
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestCoroutineScheduler
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlin.test.Test

Expand All @@ -27,6 +33,28 @@ class ChannelTransportTest {
sendChannel.receive() shouldBe message
}

@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `answers a request the peer sent before start returned`() = runTest {
val loopScheduler = TestCoroutineScheduler()
val sendChannel = Channel<JSONRPCMessage>(Channel.UNLIMITED)
val receiveChannel = Channel<JSONRPCMessage>(Channel.UNLIMITED)
val transport = ChannelTransport(sendChannel, receiveChannel, StandardTestDispatcher(loopScheduler))
val request = JSONRPCRequest(RequestId.NumberId(1), "ping")
val response = JSONRPCResponse(request.id)
transport.onMessage { transport.send(response) }
receiveChannel.send(request)

val start = launch { transport.start() }
runCurrent()
loopScheduler.runCurrent()
runCurrent()
loopScheduler.runCurrent()

start.isCompleted shouldBe true
sendChannel.tryReceive().getOrNull() shouldBe response
}

@Test
fun `start reads from receiveChannel and invokes onMessage`() = runTest {
val receiveChannel = Channel<JSONRPCMessage>(Channel.UNLIMITED)
Expand Down
Loading