File tree Expand file tree Collapse file tree 3 files changed +41
-4
lines changed
commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client Expand file tree Collapse file tree 3 files changed +41
-4
lines changed Original file line number Diff line number Diff line change @@ -40,7 +40,18 @@ public class SSEClientTransport(
4040 private var job: Job ? = null
4141
4242 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+ }
4455 }
4556
4657 override suspend fun start () {
@@ -80,8 +91,7 @@ public class SSEClientTransport(
8091 val eventData = event.data ? : " "
8192
8293 // check url correctness
83- val maybeEndpoint = Url (" $baseUrl /$eventData " )
84-
94+ val maybeEndpoint = Url (" $baseUrl /${if (eventData.startsWith(" /" )) eventData.substring(1 ) else eventData} " )
8595 endpoint.complete(maybeEndpoint.toString())
8696 } catch (e: Exception ) {
8797 onError?.invoke(e)
Original file line number Diff line number Diff line change @@ -63,4 +63,31 @@ class SseTransportTest : BaseTransportTest() {
6363 testClientRead(client)
6464 server.stop()
6565 }
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+ }
6693}
Original file line number Diff line number Diff line change @@ -71,8 +71,8 @@ fun Route.mcpSseTransport(
7171) {
7272 sse(path) {
7373 val transport = createMcpTransport(this , incomingPath)
74- transport.start()
7574 handler(transport)
75+ transport.start()
7676 transport.close()
7777 }
7878
You can’t perform that action at this time.
0 commit comments