Skip to content

Commit 0989362

Browse files
devcrocodPavel Gorgulov
authored andcommitted
clean up code
1 parent 958eef5 commit 0989362

File tree

11 files changed

+41
-26
lines changed

11 files changed

+41
-26
lines changed

src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client/Client.kt

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public class ClientOptions(
5959
* An MCP client on top of a pluggable transport.
6060
*
6161
* The client automatically performs the initialization handshake with the server when [connect] is called.
62-
* After initialization, [severCapabilities] and [serverVersion] provide details about the connected server.
62+
* After initialization, [serverCapabilities] and [serverVersion] provide details about the connected server.
6363
*
6464
* You can extend this class with custom request/notification/result types if needed.
6565
*
@@ -167,9 +167,7 @@ public open class Client(
167167
Method.Defined.ResourcesUnsubscribe,
168168
-> {
169169
val resCaps = serverCapabilities?.resources
170-
if (resCaps == null) {
171-
throw IllegalStateException("Server does not support resources (required for $method)")
172-
}
170+
?: error("Server does not support resources (required for $method)")
173171

174172
if (method == Method.Defined.ResourcesSubscribe && resCaps.subscribe != true) {
175173
throw IllegalStateException(

src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client/SSEClientTransport.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public class SseClientTransport(
5959
}
6060

6161
override suspend fun start() {
62-
if (!initialized.compareAndSet(false, true)) {
62+
if (!initialized.compareAndSet(expectedValue = false, newValue = true)) {
6363
error(
6464
"SSEClientTransport already started! " +
6565
"If using Client class, note that connect() calls start() automatically.",

src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/SSEServerTransport.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public class SseServerTransport(
4545
*/
4646
override suspend fun start() {
4747
if (!initialized.compareAndSet(expectedValue = false, newValue = true)) {
48-
throw error("SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.")
48+
error("SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.")
4949
}
5050

5151
// Send the endpoint event
@@ -117,7 +117,7 @@ public class SseServerTransport(
117117

118118
override suspend fun send(message: JSONRPCMessage) {
119119
if (!initialized.load()) {
120-
throw error("Not connected")
120+
error("Not connected")
121121
}
122122

123123
session.send(

src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/StdioServerTransport.kt

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@ import io.modelcontextprotocol.kotlin.sdk.shared.ReadBuffer
88
import io.modelcontextprotocol.kotlin.sdk.shared.serializeMessage
99
import kotlinx.coroutines.CoroutineScope
1010
import kotlinx.coroutines.Job
11+
import kotlinx.coroutines.NonCancellable
1112
import kotlinx.coroutines.SupervisorJob
13+
import kotlinx.coroutines.cancelAndJoin
1214
import kotlinx.coroutines.channels.Channel
1315
import kotlinx.coroutines.isActive
1416
import kotlinx.coroutines.launch
17+
import kotlinx.coroutines.withContext
1518
import kotlinx.io.Buffer
1619
import kotlinx.io.Sink
1720
import kotlinx.io.Source
@@ -123,15 +126,26 @@ public class StdioServerTransport(
123126
override suspend fun close() {
124127
if (!initialized.compareAndSet(expectedValue = true, newValue = false)) return
125128

126-
// Cancel reading job and close channel
127-
readingJob?.cancel() // ToDO("was cancel and join")
128-
sendingJob?.cancel()
129+
withContext(NonCancellable) {
130+
writeChannel.close()
131+
sendingJob?.cancelAndJoin()
129132

130-
readChannel.close()
131-
writeChannel.close()
132-
readBuffer.clear()
133+
runCatching {
134+
inputStream.close()
135+
}.onFailure { logger.warn(it) { "Failed to close stdin" } }
133136

134-
_onClose.invoke()
137+
readingJob?.cancel()
138+
139+
readChannel.close()
140+
readBuffer.clear()
141+
142+
runCatching {
143+
outputWriter.flush()
144+
outputWriter.close()
145+
}.onFailure { logger.warn(it) { "Failed to close stdout" } }
146+
147+
_onClose.invoke()
148+
}
135149
}
136150

137151
override suspend fun send(message: JSONRPCMessage) {

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,8 @@ public open class ProtocolOptions(
6969
* considered a logic error to mis-specify those.
7070
*
7171
* Currently, this defaults to false, for backwards compatibility with SDK versions
72-
* that did not advertise capabilities correctly. In future, this will default to true.
72+
* that did not advertise capabilities correctly.
73+
* In the future, this will default to true.
7374
*/
7475
public var enforceStrictCapabilities: Boolean = false,
7576

@@ -140,7 +141,8 @@ public abstract class Protocol(
140141
/**
141142
* Callback for when an error occurs.
142143
*
143-
* Note that errors are not necessarily fatal they are used for reporting any kind of exceptional condition out of band.
144+
* Note that errors are not necessarily fatal they are used
145+
* for reporting any kind of exceptional condition out of a band.
144146
*/
145147
public open fun onError(error: Throwable) {}
146148

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import io.modelcontextprotocol.kotlin.sdk.JSONRPCMessage
44
import kotlinx.coroutines.CompletableDeferred
55

66
/**
7-
* Describes the minimal contract for a MCP transport that a client or server can communicate over.
7+
* Describes the minimal contract for MCP transport that a client or server can communicate over.
88
*/
99
public interface Transport {
1010
/**
@@ -38,7 +38,7 @@ public interface Transport {
3838
* Callback for when an error occurs.
3939
*
4040
* Note that errors are not necessarily fatal; they are used for reporting any kind of
41-
* exceptional condition out of band.
41+
* exceptional condition out of a band.
4242
*/
4343
public fun onError(block: (Throwable) -> Unit)
4444

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public abstract class WebSocketMcpTransport : AbstractTransport() {
4141
protected abstract suspend fun initializeSession()
4242

4343
override suspend fun start() {
44-
if (!initialized.compareAndSet(false, true)) {
44+
if (!initialized.compareAndSet(expectedValue = false, newValue = true)) {
4545
error(
4646
"WebSocketClientTransport already started! " +
4747
"If using Client class, note that connect() calls start() automatically.",

src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ internal fun JSONRPCNotification.fromJSON(): Notification {
183183
public sealed interface RequestResult : WithMeta
184184

185185
/**
186-
* An empty result for a request, containing optional metadata.
186+
* An empty result for a request containing optional metadata.
187187
*
188188
* @param _meta Additional metadata for the response. Defaults to an empty JSON object.
189189
*/
@@ -492,7 +492,8 @@ public class InitializedNotification : ClientNotification {
492492

493493
/* Ping */
494494
/**
495-
* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.
495+
* A ping, issued by either the server or the client, to check that the other party is still alive.
496+
* The receiver must promptly respond, or else it may be disconnected.
496497
*/
497498
@Serializable
498499
public class PingRequest : ServerRequest, ClientRequest {

src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/ReadBufferTest.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,12 @@ class ReadBufferTest {
2828
fun `should only yield a message after a newline`() {
2929
val readBuffer = ReadBuffer()
3030

31-
// Append message without newline
31+
// Append message without a newline
3232
val messageBytes = json.encodeToString(testMessage).encodeToByteArray()
3333
readBuffer.append(messageBytes)
3434
assertNull(readBuffer.readMessage())
3535

36-
// Append newline and verify message is now available
36+
// Append a newline and verify message is now available
3737
readBuffer.append("\n".encodeToByteArray())
3838
assertEquals(testMessage, readBuffer.readMessage())
3939
assertNull(readBuffer.readMessage())

src/jvmTest/kotlin/client/ClientTest.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -486,10 +486,10 @@ class ClientTest {
486486

487487
server.setRequestHandler<ListResourcesRequest>(Method.Defined.ResourcesList) { _, extra ->
488488
// Simulate a delayed response
489-
// Wait ~100ms unless cancelled
489+
// Wait ~100ms unless canceled
490490
try {
491491
kotlinx.coroutines.withTimeout(100L) {
492-
// Just delay here, if timeout is 0 on client side this won't return in time
492+
// Just delay here, if timeout is 0 on the client side, this won't return in time
493493
kotlinx.coroutines.delay(100)
494494
}
495495
} catch (_: Exception) {

0 commit comments

Comments
 (0)