|
| 1 | +package io.modelcontextprotocol.kotlin.sdk.integration |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import io.ktor.client.HttpClient |
| 5 | +import io.ktor.client.request.get |
| 6 | +import io.ktor.http.HttpStatusCode |
| 7 | +import io.ktor.serialization.kotlinx.json.json |
| 8 | +import io.ktor.server.application.Application |
| 9 | +import io.ktor.server.application.ApplicationCall |
| 10 | +import io.ktor.server.application.install |
| 11 | +import io.ktor.server.auth.Authentication |
| 12 | +import io.ktor.server.auth.UserIdPrincipal |
| 13 | +import io.ktor.server.auth.authenticate |
| 14 | +import io.ktor.server.auth.basic |
| 15 | +import io.ktor.server.auth.principal |
| 16 | +import io.ktor.server.engine.embeddedServer |
| 17 | +import io.ktor.server.plugins.contentnegotiation.ContentNegotiation |
| 18 | +import io.ktor.server.routing.Route |
| 19 | +import io.ktor.server.routing.routing |
| 20 | +import io.modelcontextprotocol.kotlin.sdk.client.Client |
| 21 | +import io.modelcontextprotocol.kotlin.sdk.server.Server |
| 22 | +import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions |
| 23 | +import io.modelcontextprotocol.kotlin.sdk.shared.Transport |
| 24 | +import io.modelcontextprotocol.kotlin.sdk.types.Implementation |
| 25 | +import io.modelcontextprotocol.kotlin.sdk.types.McpJson |
| 26 | +import io.modelcontextprotocol.kotlin.sdk.types.ReadResourceRequest |
| 27 | +import io.modelcontextprotocol.kotlin.sdk.types.ReadResourceRequestParams |
| 28 | +import io.modelcontextprotocol.kotlin.sdk.types.ReadResourceResult |
| 29 | +import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities |
| 30 | +import io.modelcontextprotocol.kotlin.sdk.types.TextResourceContents |
| 31 | +import io.modelcontextprotocol.kotlin.test.utils.actualPort |
| 32 | +import kotlinx.coroutines.Dispatchers |
| 33 | +import kotlinx.coroutines.runBlocking |
| 34 | +import java.util.UUID |
| 35 | +import kotlin.test.Test |
| 36 | +import io.ktor.client.engine.cio.CIO as ClientCIO |
| 37 | +import io.ktor.server.cio.CIO as ServerCIO |
| 38 | +import io.ktor.server.sse.SSE as ServerSSE |
| 39 | + |
| 40 | +/** |
| 41 | + * Base class for MCP authentication integration tests. |
| 42 | + * |
| 43 | + * This class provides a common setup for testing MCP servers behind Ktor authentication. |
| 44 | + * It verifies that unauthenticated requests are rejected and that the authenticated principal |
| 45 | + * is accessible within MCP resource handlers. |
| 46 | + */ |
| 47 | +abstract class AbstractAuthenticationTest { |
| 48 | + |
| 49 | + protected companion object { |
| 50 | + const val HOST = "127.0.0.1" |
| 51 | + const val AUTH_REALM = "mcp-auth" |
| 52 | + const val WHOAMI_URI = "whoami://me" |
| 53 | + } |
| 54 | + |
| 55 | + protected val validUser: String = "user-${UUID.randomUUID().toString().take(8)}" |
| 56 | + protected val validPassword: String = UUID.randomUUID().toString() |
| 57 | + |
| 58 | + /** |
| 59 | + * Installs Ktor plugins required by the transport under test. |
| 60 | + * |
| 61 | + * The default installs [ServerSSE] (required by both SSE and StreamableHttp transports) |
| 62 | + * and [ContentNegotiation] with [McpJson] (required by StreamableHttp for JSON body |
| 63 | + * serialization). Subclasses may override to add transport-specific plugins. |
| 64 | + */ |
| 65 | + protected open fun Application.configurePlugins() { |
| 66 | + install(ServerSSE) |
| 67 | + // ContentNegotiation is required by the StreamableHttp transport for JSON body handling. |
| 68 | + // Installing it for SSE tests as well is harmless. |
| 69 | + install(ContentNegotiation) { json(McpJson) } |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Registers the MCP server on the given route. |
| 74 | + * Concrete implementations should use transport-specific extensions (e.g., [Route.mcp] for SSE). |
| 75 | + */ |
| 76 | + abstract fun Route.registerMcpServer(serverFactory: ApplicationCall.() -> Server) |
| 77 | + |
| 78 | + /** |
| 79 | + * Creates a client transport configured with the given credentials. |
| 80 | + */ |
| 81 | + abstract fun createClientTransport(baseUrl: String, user: String, pass: String): Transport |
| 82 | + |
| 83 | + @Test |
| 84 | + fun `mcp behind basic auth rejects unauthenticated requests with 401`() { |
| 85 | + runBlocking(Dispatchers.IO) { |
| 86 | + val server = embeddedServer(ServerCIO, host = HOST, port = 0) { |
| 87 | + configurePlugins() |
| 88 | + install(Authentication) { |
| 89 | + basic(AUTH_REALM) { |
| 90 | + validate { credentials -> |
| 91 | + if (credentials.name == validUser && credentials.password == validPassword) { |
| 92 | + UserIdPrincipal(credentials.name) |
| 93 | + } else { |
| 94 | + null |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + routing { |
| 100 | + authenticate(AUTH_REALM) { |
| 101 | + registerMcpServer { |
| 102 | + createMcpServer { principal<UserIdPrincipal>()?.name } |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + }.startSuspend(wait = false) |
| 107 | + |
| 108 | + val httpClient = HttpClient(ClientCIO) |
| 109 | + try { |
| 110 | + httpClient.get("http://$HOST:${server.actualPort()}").status shouldBe HttpStatusCode.Unauthorized |
| 111 | + } finally { |
| 112 | + httpClient.close() |
| 113 | + server.stopSuspend(500, 1000) |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + @Test |
| 119 | + fun `authenticated mcp client can read resource scoped to principal`() { |
| 120 | + runBlocking(Dispatchers.IO) { |
| 121 | + val server = embeddedServer(ServerCIO, host = HOST, port = 0) { |
| 122 | + configurePlugins() |
| 123 | + install(Authentication) { |
| 124 | + basic(AUTH_REALM) { |
| 125 | + validate { credentials -> |
| 126 | + if (credentials.name == validUser && credentials.password == validPassword) { |
| 127 | + UserIdPrincipal(credentials.name) |
| 128 | + } else { |
| 129 | + null |
| 130 | + } |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + routing { |
| 135 | + authenticate(AUTH_REALM) { |
| 136 | + registerMcpServer { |
| 137 | + // `this` is the ApplicationCall at connection time. |
| 138 | + // The lambda passed to createMcpServer captures this call; |
| 139 | + // principal<T>() is safe to call from resource handlers because |
| 140 | + // the call's authentication context remains valid for the session lifetime. |
| 141 | + createMcpServer { principal<UserIdPrincipal>()?.name } |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + }.startSuspend(wait = false) |
| 146 | + |
| 147 | + val baseUrl = "http://$HOST:${server.actualPort()}" |
| 148 | + var mcpClient: Client? = null |
| 149 | + try { |
| 150 | + mcpClient = Client(Implementation(name = "test-client", version = "1.0.0")) |
| 151 | + mcpClient.connect(createClientTransport(baseUrl, validUser, validPassword)) |
| 152 | + |
| 153 | + val result = mcpClient.readResource( |
| 154 | + ReadResourceRequest(ReadResourceRequestParams(uri = WHOAMI_URI)), |
| 155 | + ) |
| 156 | + |
| 157 | + result.contents shouldBe listOf( |
| 158 | + TextResourceContents( |
| 159 | + text = validUser, |
| 160 | + uri = WHOAMI_URI, |
| 161 | + mimeType = "text/plain", |
| 162 | + ), |
| 163 | + ) |
| 164 | + } finally { |
| 165 | + mcpClient?.close() |
| 166 | + server.stopSuspend(500, 1000) |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + protected fun createMcpServer(principalProvider: () -> String?): Server = Server( |
| 172 | + serverInfo = Implementation(name = "test-server", version = "1.0.0"), |
| 173 | + options = ServerOptions( |
| 174 | + capabilities = ServerCapabilities( |
| 175 | + resources = ServerCapabilities.Resources(), |
| 176 | + ), |
| 177 | + ), |
| 178 | + ).apply { |
| 179 | + addResource( |
| 180 | + uri = WHOAMI_URI, |
| 181 | + name = "Current User", |
| 182 | + description = "Returns the name of the authenticated user", |
| 183 | + mimeType = "text/plain", |
| 184 | + ) { |
| 185 | + ReadResourceResult( |
| 186 | + contents = listOf( |
| 187 | + TextResourceContents( |
| 188 | + text = principalProvider() ?: "anonymous", |
| 189 | + uri = WHOAMI_URI, |
| 190 | + mimeType = "text/plain", |
| 191 | + ), |
| 192 | + ), |
| 193 | + ) |
| 194 | + } |
| 195 | + } |
| 196 | +} |
0 commit comments