Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -571,17 +571,23 @@ private fun Route.installCancelCallOnClose() {
}
}

/** Checks the session of a GET before sse {}, which sends 200 and the headers before its handler runs. */
/**
* Checks the `Accept` header, session and protocol version of a GET before sse {}, which sends 200 and the headers
* before its handler runs.
*/
private fun Route.installGetSessionGuard(sessions: StreamableHttpSessionManager<StreamableHttpServerTransport>) {
val guard = createRouteScopedPlugin("MCP-StreamableHttpGetSessionGuard") {
onCall { call ->
if (call.request.httpMethod != HttpMethod.Get || call.isHandled) return@onCall
if (!call.validateAcceptsEventStream()) return@onCall
val sessionId = call.sessionIdOrReject() ?: return@onCall
// Touched so that the session cannot expire before sse {} runs.
if (sessions.touch(sessionId) == null) {
val transport = sessions.touch(sessionId)
if (transport == null) {
call.rejectSessionNotFound()
return@onCall
}
if (!transport.validateProtocolVersion(call)) return@onCall
call.response.header(MCP_SESSION_ID_HEADER, sessionId)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -614,15 +614,7 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
// for server-to-client notifications when enableJsonResponse = true.
val sseSession = session ?: error("Server session can't be null for streaming GET requests")

val acceptHeader = call.request.header(HttpHeaders.Accept)
if (!acceptHeader.accepts(ContentType.Text.EventStream)) {
call.reject(
HttpStatusCode.NotAcceptable,
RPCError.ErrorCode.CONNECTION_CLOSED,
"Not Acceptable: Client must accept text/event-stream",
)
return
}
if (!call.validateAcceptsEventStream()) return

if (!validateSession(call) || !validateProtocolVersion(call)) return

Expand Down Expand Up @@ -782,7 +774,7 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
return true
}

private suspend fun validateProtocolVersion(call: ApplicationCall, id: RequestId? = null): Boolean {
internal suspend fun validateProtocolVersion(call: ApplicationCall, id: RequestId? = null): Boolean {
val version = call.request.headers[MCP_PROTOCOL_VERSION_HEADER] ?: return true

return when (version) {
Expand Down Expand Up @@ -871,25 +863,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
}

/**
* Reports whether the `Accept` header admits [mime].
*
* Comparison is over parsed media ranges rather than raw substrings, so wildcards are honored
* and a near miss such as `application/jsonp` no longer passes as `application/json`. An absent
* header states no preference and admits any type.
*/
private fun String?.accepts(mime: ContentType): Boolean {
if (this == null) return true
return parseHeaderValue(this).any { range ->
if (range.quality <= 0.0) return@any false
try {
mime.match(ContentType.parse(range.value))
} catch (_: BadContentTypeFormatException) {
false
}
}
}

private suspend fun emitOnStream(streamId: String, session: ServerSSESession?, message: JSONRPCMessage) {
val eventId = configuration.eventStore?.storeEvent(streamId, message)
try {
Expand Down Expand Up @@ -962,6 +935,36 @@ internal suspend fun ApplicationCall.rejectSessionNotFound(id: RequestId? = null
reject(HttpStatusCode.NotFound, REQUEST_TIMEOUT, "Session not found", id)
}

/** Answers `406 Not Acceptable` and returns `false` unless the `Accept` header admits `text/event-stream`. */
internal suspend fun ApplicationCall.validateAcceptsEventStream(): Boolean {
if (request.header(HttpHeaders.Accept).accepts(ContentType.Text.EventStream)) return true
reject(
HttpStatusCode.NotAcceptable,
RPCError.ErrorCode.CONNECTION_CLOSED,
"Not Acceptable: Client must accept text/event-stream",
)
return false
}

/**
* Reports whether the `Accept` header admits [mime].
*
* Comparison is over parsed media ranges rather than raw substrings, so wildcards are honored
* and a near miss such as `application/jsonp` no longer passes as `application/json`. An absent
* header states no preference and admits any type.
*/
private fun String?.accepts(mime: ContentType): Boolean {
if (this == null) return true
return parseHeaderValue(this).any { range ->
if (range.quality <= 0.0) return@any false
try {
mime.match(ContentType.parse(range.value))
} catch (_: BadContentTypeFormatException) {
false
}
}
}

/** Closes this session, ignoring failures and giving up after [SSE_SESSION_CLOSE_TIMEOUT]. */
private suspend fun ServerSSESession.closeQuietly() {
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package io.modelcontextprotocol.kotlin.sdk.server

import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldStartWith
import io.ktor.client.HttpClient
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.request
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
Expand All @@ -17,6 +22,7 @@ import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import io.ktor.server.testing.testApplication
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCError
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.McpJson
import io.modelcontextprotocol.kotlin.sdk.types.RPCError
import org.junit.jupiter.params.ParameterizedTest
Expand Down Expand Up @@ -91,6 +97,43 @@ class StreamableHttpResponseDeliveryTest {
response.status shouldBe HttpStatusCode.BadRequest
}

@Test
fun `stateful GET whose Accept header excludes event-stream returns 406`() = testApplication {
application { mcpStreamableHttp { testServer() } }
val sessionId = client.initialize()

val response = client.get("/mcp") {
header(HttpHeaders.Host, "localhost")
header(HttpHeaders.Accept, ContentType.Application.Json.toString())
header(MCP_SESSION_ID_HEADER, sessionId)
}

response.status shouldBe HttpStatusCode.NotAcceptable
response.contentType()?.withoutParameters() shouldBe ContentType.Application.Json
val error = response.decodeError().error
error.message shouldBe "Not Acceptable: Client must accept text/event-stream"
error.code shouldBe RPCError.ErrorCode.CONNECTION_CLOSED
}

@Test
fun `stateful GET with an unsupported protocol version returns 400`() = testApplication {
application { mcpStreamableHttp { testServer() } }
val sessionId = client.initialize()

val response = client.get("/mcp") {
header(HttpHeaders.Host, "localhost")
header(HttpHeaders.Accept, eventStream)
header(MCP_SESSION_ID_HEADER, sessionId)
header("mcp-protocol-version", "1900-01-01")
}

response.status shouldBe HttpStatusCode.BadRequest
response.contentType()?.withoutParameters() shouldBe ContentType.Application.Json
val error = response.decodeError().error
error.message shouldStartWith "Bad Request: Unsupported protocol version"
error.code shouldBe RPCError.ErrorCode.CONNECTION_CLOSED
}

@Test
fun `GET routes next to the stateful endpoint are not checked for a session`() = testApplication {
application {
Expand All @@ -104,5 +147,15 @@ class StreamableHttpResponseDeliveryTest {
response.bodyAsText() shouldBe "ok"
}

private suspend fun HttpClient.initialize(): String {
val response = post("/mcp") {
header(HttpHeaders.Host, "localhost")
streamableHeaders()
setBody(McpJson.encodeToString(JSONRPCMessage.serializer(), initializeRequest()))
}
response.status shouldBe HttpStatusCode.OK
return response.headers[MCP_SESSION_ID_HEADER].shouldNotBeNull()
}

private suspend fun HttpResponse.decodeError(): JSONRPCError = McpJson.decodeFromString(bodyAsText())
}