11package io.modelcontextprotocol.kotlin.sdk.integration
22
33import io.ktor.client.HttpClient
4- import io.ktor.client.plugins.sse.SSE
54import io.ktor.server.application.install
65import io.ktor.server.cio.CIOApplicationEngine
76import io.ktor.server.engine.EmbeddedServer
@@ -20,36 +19,32 @@ import kotlinx.coroutines.withContext
2019import kotlin.test.Test
2120import kotlin.test.fail
2221import io.ktor.client.engine.cio.CIO as ClientCIO
22+ import io.ktor.client.plugins.sse.SSE as ClientSSE
2323import io.ktor.server.cio.CIO as ServerCIO
24+ import io.ktor.server.sse.SSE as ServerSSE
25+
26+ private const val URL = " 127.0.0.1"
2427
2528class SseIntegrationTest {
2629 @Test
2730 fun `client should be able to connect to sse server` () = runTest {
2831 val serverEngine = initServer()
29- var client: Client ? = null
3032 try {
3133 withContext(Dispatchers .Default ) {
32- assertDoesNotThrow { client = initClient() }
34+ val port = serverEngine.engine.resolvedConnectors().first().port
35+ val client = initClient(port)
36+ client.close()
3337 }
3438 } catch (e: Exception ) {
3539 fail(" Failed to connect client: $e " )
3640 } finally {
37- client?.close()
3841 // Make sure to stop the server
3942 serverEngine.stopSuspend(1000 , 2000 )
4043 }
4144 }
4245
43- private inline fun <T > assertDoesNotThrow (block : () -> T ): T {
44- return try {
45- block()
46- } catch (e: Throwable ) {
47- fail(" Expected no exception, but got: $e " )
48- }
49- }
50-
51- private suspend fun initClient (): Client {
52- return HttpClient (ClientCIO ) { install(SSE ) }.mcpSse(" http://$URL :$PORT " )
46+ private suspend fun initClient (port : Int ): Client {
47+ return HttpClient (ClientCIO ) { install(ClientSSE ) }.mcpSse(" http://$URL :$port " )
5348 }
5449
5550 private suspend fun initServer (): EmbeddedServer <CIOApplicationEngine , CIOApplicationEngine .Configuration > {
@@ -58,16 +53,11 @@ class SseIntegrationTest {
5853 ServerOptions (capabilities = ServerCapabilities ()),
5954 )
6055
61- return embeddedServer(ServerCIO , host = URL , port = PORT ) {
62- install(io.ktor.server.sse. SSE )
56+ return embeddedServer(ServerCIO , host = URL , port = 0 ) {
57+ install(ServerSSE )
6358 routing {
6459 mcp { server }
6560 }
6661 }.startSuspend(wait = false )
6762 }
68-
69- companion object {
70- private const val PORT = 3001
71- private const val URL = " localhost"
72- }
7363}
0 commit comments