File tree Expand file tree Collapse file tree 2 files changed +50
-3
lines changed
commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client Expand file tree Collapse file tree 2 files changed +50
-3
lines changed Original file line number Diff line number Diff line change @@ -39,7 +39,18 @@ public class SseClientTransport(
3939 private var job: Job ? = null
4040
4141 private val baseUrl by lazy {
42- session.call.request.url.toString().removeSuffix(" /" )
42+ val requestUrl = session.call.request.url.toString()
43+ val url = Url (requestUrl)
44+ var path = url.encodedPath
45+ if (path.isEmpty()) {
46+ url.protocolWithAuthority
47+ } else if (path.endsWith(" /" )) {
48+ url.protocolWithAuthority + path.removeSuffix(" /" )
49+ } else {
50+ // the last item is not a directory, so will not be taken into account
51+ path = path.substring(0 , path.lastIndexOf(" /" ))
52+ url.protocolWithAuthority + path
53+ }
4354 }
4455
4556 override suspend fun start () {
@@ -79,8 +90,7 @@ public class SseClientTransport(
7990 val eventData = event.data ? : " "
8091
8192 // check url correctness
82- val maybeEndpoint = Url (" $baseUrl /$eventData " )
83-
93+ val maybeEndpoint = Url (" $baseUrl /${if (eventData.startsWith(" /" )) eventData.substring(1 ) else eventData} " )
8494 endpoint.complete(maybeEndpoint.toString())
8595 } catch (e: Exception ) {
8696 _onError (e)
Original file line number Diff line number Diff line change @@ -82,4 +82,41 @@ class SseTransportTest : BaseTransportTest() {
8282 testClientRead(client)
8383 server.stop()
8484 }
85+
86+ @Test
87+ fun `test sse path not root path` () = runTest {
88+ val server = embeddedServer(CIO , port = PORT ) {
89+ install(io.ktor.server.sse.SSE )
90+ val transports = ConcurrentMap <String , SseServerTransport >()
91+ routing {
92+ sse(" /sse" ) {
93+ mcpSseTransport(" /messages" , transports).apply {
94+ onMessage {
95+ send(it)
96+ }
97+
98+ start()
99+ }
100+ }
101+
102+ post(" /messages" ) {
103+
104+ mcpPostEndpoint(transports)
105+ }
106+ }
107+ }.start(wait = false )
108+
109+ val client = HttpClient {
110+ install(SSE )
111+ }.mcpSseTransport {
112+ url {
113+ host = " localhost"
114+ port = PORT
115+ pathSegments = listOf (" sse" )
116+ }
117+ }
118+
119+ testClientRead(client)
120+ server.stop()
121+ }
85122}
You can’t perform that action at this time.
0 commit comments