File tree 3 files changed +41
-4
lines changed
commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client
3 files changed +41
-4
lines changed Original file line number Diff line number Diff line change @@ -40,7 +40,18 @@ public class SSEClientTransport(
40
40
private var job: Job ? = null
41
41
42
42
private val baseUrl by lazy {
43
- session.call.request.url.toString().removeSuffix(" /" )
43
+ val requestUrl = session.call.request.url.toString()
44
+ val url = Url (requestUrl)
45
+ var path = url.encodedPath
46
+ if (path.isEmpty()) {
47
+ url.protocolWithAuthority
48
+ } else if (path.endsWith(" /" )) {
49
+ url.protocolWithAuthority + path.removeSuffix(" /" )
50
+ } else {
51
+ // the last item is not a directory, so will not be taken into account
52
+ path = path.substring(0 , path.lastIndexOf(" /" ))
53
+ url.protocolWithAuthority + path
54
+ }
44
55
}
45
56
46
57
override suspend fun start () {
@@ -80,8 +91,7 @@ public class SSEClientTransport(
80
91
val eventData = event.data ? : " "
81
92
82
93
// check url correctness
83
- val maybeEndpoint = Url (" $baseUrl /$eventData " )
84
-
94
+ val maybeEndpoint = Url (" $baseUrl /${if (eventData.startsWith(" /" )) eventData.substring(1 ) else eventData} " )
85
95
endpoint.complete(maybeEndpoint.toString())
86
96
} catch (e: Exception ) {
87
97
onError?.invoke(e)
Original file line number Diff line number Diff line change @@ -63,4 +63,31 @@ class SseTransportTest : BaseTransportTest() {
63
63
testClientRead(client)
64
64
server.stop()
65
65
}
66
+
67
+ @Test
68
+ fun `test sse path not root path` () = runTest {
69
+ val server = embeddedServer(CIO , port = PORT ) {
70
+ install(io.ktor.server.sse.SSE )
71
+ routing {
72
+ mcpSseTransport(path = " /sse" , incomingPath = " /messages" ) {
73
+ onMessage = {
74
+ send(it)
75
+ }
76
+ }
77
+ }
78
+ }.start(wait = false )
79
+
80
+ val client = HttpClient {
81
+ install(SSE )
82
+ }.mcpSseTransport {
83
+ url {
84
+ host = " localhost"
85
+ port = PORT
86
+ pathSegments = listOf (" sse" )
87
+ }
88
+ }
89
+
90
+ testClientRead(client)
91
+ server.stop()
92
+ }
66
93
}
Original file line number Diff line number Diff line change @@ -71,8 +71,8 @@ fun Route.mcpSseTransport(
71
71
) {
72
72
sse(path) {
73
73
val transport = createMcpTransport(this , incomingPath)
74
- transport.start()
75
74
handler(transport)
75
+ transport.start()
76
76
transport.close()
77
77
}
78
78
You can’t perform that action at this time.
0 commit comments