Skip to content

Commit cc501db

Browse files
committed
Fix AbstractTransport to not skip messages
1 parent 70a11d4 commit cc501db

File tree

1 file changed

+18
-2
lines changed
  • src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared

1 file changed

+18
-2
lines changed

src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Transport.kt

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.modelcontextprotocol.kotlin.sdk.shared
22

33
import io.modelcontextprotocol.kotlin.sdk.JSONRPCMessage
4+
import kotlinx.coroutines.CompletableDeferred
45

56
/**
67
* Describes the minimal contract for a MCP transport that a client or server can communicate over.
@@ -54,8 +55,17 @@ public interface Transport {
5455
@Suppress("PropertyName")
5556
public abstract class AbstractTransport : Transport {
5657
protected var _onClose: (() -> Unit) = {}
58+
private set
5759
protected var _onError: ((Throwable) -> Unit) = {}
58-
protected var _onMessage: (suspend ((JSONRPCMessage) -> Unit)) = {}
60+
private set
61+
62+
// to not skip messages
63+
private val _onMessageInitialized = CompletableDeferred<Unit>()
64+
protected var _onMessage: (suspend ((JSONRPCMessage) -> Unit)) = {
65+
_onMessageInitialized.await()
66+
_onMessage.invoke(it)
67+
}
68+
private set
5969

6070
override fun onClose(block: () -> Unit) {
6171
val old = _onClose
@@ -74,10 +84,16 @@ public abstract class AbstractTransport : Transport {
7484
}
7585

7686
override fun onMessage(block: suspend (JSONRPCMessage) -> Unit) {
77-
val old = _onMessage
87+
val old: suspend (JSONRPCMessage) -> Unit = when (_onMessageInitialized.isCompleted) {
88+
true -> _onMessage
89+
false -> { _ -> }
90+
}
91+
7892
_onMessage = { message ->
7993
old(message)
8094
block(message)
8195
}
96+
97+
_onMessageInitialized.complete(Unit)
8298
}
8399
}

0 commit comments

Comments
 (0)