sample: kotlinlang mcp server (#713)

add new sample: kotlinlang mcp server with 2 tools
- search
- get_page

## How Has This Been Tested?
inspector/unit

## Breaking Changes
none

## Checklist
- [x] I have read the [MCP
Documentation](https://modelcontextprotocol.io)
- [x] My code follows the repository's style guidelines
- [x] New and existing tests pass locally
- [x] I have added appropriate error handling
- [x] I have added or updated documentation as needed
This commit is contained in:
Pavel Gorgulov 2026-04-27 15:07:03 +02:00 • committed by GitHub
commit c946dfc3c2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 2149 additions and 0 deletions

View file

@ -0,0 +1,62 @@
package org.kotlinlang.mcp
import io.modelcontextprotocol.kotlin.sdk.ExperimentalMcpApi
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.ClientOptions
import io.modelcontextprotocol.kotlin.sdk.testing.ChannelTransport
import io.modelcontextprotocol.kotlin.sdk.types.Implementation
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import org.kotlinlang.mcp.config.ServerConfig
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@OptIn(ExperimentalMcpApi::class)
class KotlinlangServerTest {
private val testConfig = ServerConfig(
algoliaAppId = "test-app-id",
algoliaApiKey = "test-api-key",
algoliaIndexName = "test-index",
)
@Test
fun `server registers both tools with correct schema and annotations`() = runTest {
val kotlinlangServer = KotlinlangServer(testConfig)
kotlinlangServer.use {
val (clientTransport, serverTransport) = ChannelTransport.createLinkedPair()
val client = Client(
clientInfo = Implementation(name = "test-client", version = "1.0"),
options = ClientOptions(),
)
joinAll(
launch { client.connect(clientTransport) },
launch { kotlinlangServer.server.createSession(serverTransport) },
)
val tools = client.listTools().tools
assertEquals(2, tools.size)
val searchTool = tools.find { it.name == "search_kotlinlang" }
val searchProps = searchTool?.inputSchema?.properties
assertTrue(searchProps?.containsKey("query") ?: false)
assertEquals(listOf("query"), searchTool.inputSchema.required)
assertEquals(true, searchTool.annotations?.readOnlyHint)
assertEquals(true, searchTool.annotations?.openWorldHint)
val pageTool = tools.find { it.name == "get_kotlinlang_page" }
val pageProps = pageTool?.inputSchema?.properties
assertTrue(pageProps?.containsKey("path") ?: false)
assertEquals(listOf("path"), pageTool.inputSchema.required)
assertEquals(true, pageTool.annotations?.readOnlyHint)
assertEquals(true, pageTool.annotations?.openWorldHint)
client.close()
}
}
}

View file

@ -0,0 +1,166 @@
package org.kotlinlang.mcp.algolia
import io.ktor.client.*
import io.ktor.client.engine.mock.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import org.kotlinlang.mcp.config.ServerConfig
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class AlgoliaClientTest {
private val testConfig = ServerConfig(
algoliaAppId = "test-app-id",
algoliaApiKey = "test-api-key",
algoliaIndexName = "test-index",
)
private val json = Json { ignoreUnknownKeys = true }
private fun createClient(mockEngine: MockEngine): AlgoliaClient {
val httpClient = HttpClient(mockEngine) {
install(ContentNegotiation) { json(json) }
expectSuccess = true
}
return AlgoliaClient(testConfig, httpClient)
}
@Test
fun `search sends correct URL and headers`() = runTest {
val mockEngine = MockEngine { request ->
assertEquals(
"https://test-app-id-dsn.algolia.net/1/indexes/test-index/query",
request.url.toString(),
)
assertEquals("test-app-id", request.headers["x-algolia-application-id"])
assertEquals("test-api-key", request.headers["x-algolia-api-key"])
assertEquals(HttpMethod.Post, request.method)
respond(
content = """{"hits": []}""",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val client = createClient(mockEngine)
client.search("coroutines")
}
@Test
fun `search sends correct request body`() = runTest {
val mockEngine = MockEngine { request ->
val body = json.decodeFromString<AlgoliaSearchRequest>(request.body.toByteArray().decodeToString())
assertEquals("coroutines", body.query)
assertEquals(15, body.hitsPerPage)
assertEquals(listOf("objectID", "mainTitle", "url", "headings"), body.attributesToRetrieve)
assertEquals(listOf("content:40"), body.attributesToSnippet)
respond(
content = """{"hits": []}""",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val client = createClient(mockEngine)
client.search("coroutines")
}
@Test
fun `search parses response with hits`() = runTest {
val responseJson = """
{
"hits": [
{
"objectID": "abc123",
"mainTitle": "Coroutines overview",
"url": "/docs/coroutines-overview.html",
"headings": "Introduction | First coroutine",
"_snippetResult": {
"content": {
"value": "Kotlin provides coroutines support",
"matchLevel": "full"
}
}
}
]
}
""".trimIndent()
val mockEngine = MockEngine {
respond(
content = responseJson,
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val client = createClient(mockEngine)
val result = client.search("coroutines")
assertEquals(1, result.hits.size)
val hit = result.hits[0]
assertEquals("abc123", hit.objectID)
assertEquals("Coroutines overview", hit.mainTitle)
assertEquals("/docs/coroutines-overview.html", hit.url)
assertEquals("Introduction | First coroutine", hit.headings)
assertEquals("Kotlin provides coroutines support", hit.snippetResult?.content?.value)
assertEquals("full", hit.snippetResult?.content?.matchLevel)
}
@Test
fun `search returns empty list when no hits`() = runTest {
val mockEngine = MockEngine {
respond(
content = """{"hits": []}""",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val client = createClient(mockEngine)
val result = client.search("nonexistent")
assertTrue(result.hits.isEmpty())
}
@Test
fun `search throws on 4xx error`() = runTest {
val mockEngine = MockEngine {
respond(
content = """{"message": "Invalid Application-ID or API key"}""",
status = HttpStatusCode.Forbidden,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val client = createClient(mockEngine)
assertFailsWith<ClientRequestException> {
client.search("coroutines")
}
}
@Test
fun `search throws on 5xx error`() = runTest {
val mockEngine = MockEngine {
respond(
content = """{"message": "Internal server error"}""",
status = HttpStatusCode.InternalServerError,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val client = createClient(mockEngine)
assertFailsWith<ServerResponseException> {
client.search("coroutines")
}
}
}

View file

@ -0,0 +1,126 @@
package org.kotlinlang.mcp.algolia
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
class AlgoliaModelsTest {
private val json = Json { ignoreUnknownKeys = true }
@Test
fun `serializes search request to JSON`() {
val request = AlgoliaSearchRequest(
query = "coroutines",
hitsPerPage = 15,
attributesToRetrieve = listOf("mainTitle", "url", "headings"),
attributesToSnippet = listOf("content:40"),
)
val encoded = json.encodeToString(request)
val decoded = json.decodeFromString<AlgoliaSearchRequest>(encoded)
assertEquals(request, decoded)
}
@Test
fun `parses full response with nested snippet`() {
val responseJson = """
{
"hits": [
{
"objectID": "abc123",
"mainTitle": "Coroutines overview",
"url": "/docs/coroutines-overview.html",
"headings": "Introduction | First coroutine",
"_snippetResult": {
"content": {
"value": "Kotlin provides <em>coroutines</em> support",
"matchLevel": "full"
}
}
}
]
}
""".trimIndent()
val response = json.decodeFromString<AlgoliaSearchResponse>(responseJson)
assertEquals(1, response.hits.size)
val hit = response.hits[0]
assertEquals("abc123", hit.objectID)
assertEquals("Coroutines overview", hit.mainTitle)
assertEquals("/docs/coroutines-overview.html", hit.url)
assertEquals("Introduction | First coroutine", hit.headings)
assertEquals("Kotlin provides <em>coroutines</em> support", hit.snippetResult?.content?.value)
assertEquals("full", hit.snippetResult?.content?.matchLevel)
}
@Test
fun `parses hit with missing nullable fields`() {
val responseJson = """
{
"hits": [
{
"objectID": "def456",
"url": "/docs/basic-syntax.html"
}
]
}
""".trimIndent()
val response = json.decodeFromString<AlgoliaSearchResponse>(responseJson)
val hit = response.hits[0]
assertEquals("def456", hit.objectID)
assertEquals("/docs/basic-syntax.html", hit.url)
assertEquals(null, hit.mainTitle)
assertEquals(null, hit.headings)
assertEquals(null, hit.snippetResult)
}
@Test
fun `parses response ignoring unknown fields`() {
val responseJson = """
{
"hits": [
{
"objectID": "ghi789",
"url": "/docs/functions.html",
"unknownField": 42,
"_snippetResult": {
"content": {
"value": "snippet text",
"matchLevel": "none",
"fullyHighlighted": false
},
"anotherUnknown": "ignored"
}
}
],
"nbHits": 100,
"page": 0,
"processingTimeMS": 5
}
""".trimIndent()
val response = json.decodeFromString<AlgoliaSearchResponse>(responseJson)
assertEquals(1, response.hits.size)
assertEquals("ghi789", response.hits[0].objectID)
assertEquals("snippet text", response.hits[0].snippetResult?.content?.value)
}
@Test
fun `parses response with empty hits list`() {
val responseJson = """
{
"hits": []
}
""".trimIndent()
val response = json.decodeFromString<AlgoliaSearchResponse>(responseJson)
assertEquals(emptyList(), response.hits)
}
}

View file

@ -0,0 +1,144 @@
package org.kotlinlang.mcp.cache
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.time.Duration.Companion.minutes
import kotlin.time.TestTimeSource
class TtlCacheTest {
@Test
fun `get returns value that was put`() {
val cache = TtlCache<String, String>(ttl = 10.minutes)
cache.put("key", "value")
assertEquals("value", cache.get("key"))
}
@Test
fun `get returns null for missing key`() {
val cache = TtlCache<String, String>(ttl = 10.minutes)
assertNull(cache.get("missing"))
}
@Test
fun `get returns null after TTL expires`() {
val timeSource = TestTimeSource()
val cache = TtlCache<String, String>(ttl = 10.minutes, timeSource = timeSource)
cache.put("key", "value")
assertEquals("value", cache.get("key"))
timeSource += 11.minutes
assertNull(cache.get("key"))
}
@Test
fun `get returns value just before TTL expires`() {
val timeSource = TestTimeSource()
val cache = TtlCache<String, String>(ttl = 10.minutes, timeSource = timeSource)
cache.put("key", "value")
timeSource += 9.minutes
assertEquals("value", cache.get("key"))
}
@Test
fun `put overwrites value and resets TTL`() {
val timeSource = TestTimeSource()
val cache = TtlCache<String, String>(ttl = 10.minutes, timeSource = timeSource)
cache.put("key", "old")
timeSource += 8.minutes
cache.put("key", "new")
timeSource += 8.minutes
assertEquals("new", cache.get("key"))
}
@Test
fun `getOrPut returns cached value without calling loader`() = runTest {
val cache = TtlCache<String, String>(ttl = 10.minutes)
cache.put("key", "cached")
var loaderCalled = false
val result = cache.getOrPut("key") {
loaderCalled = true
"loaded"
}
assertEquals("cached", result)
assertEquals(false, loaderCalled)
}
@Test
fun `getOrPut calls loader on cache miss and caches result`() = runTest {
val cache = TtlCache<String, String>(ttl = 10.minutes)
val result = cache.getOrPut("key") { "loaded" }
assertEquals("loaded", result)
assertEquals("loaded", cache.get("key"))
}
@Test
fun `getOrPut calls loader again after TTL expires`() = runTest {
val timeSource = TestTimeSource()
val cache = TtlCache<String, String>(ttl = 10.minutes, timeSource = timeSource)
cache.getOrPut("key") { "first" }
timeSource += 11.minutes
val result = cache.getOrPut("key") { "second" }
assertEquals("second", result)
}
@Test
fun `put evicts expired entries`() {
val timeSource = TestTimeSource()
val cache = TtlCache<String, String>(ttl = 10.minutes, timeSource = timeSource)
cache.put("a", "1")
cache.put("b", "2")
timeSource += 11.minutes
// Both entries are expired but still in memory.
// A new put triggers eviction of expired entries.
cache.put("c", "3")
assertNull(cache.get("a"))
assertNull(cache.get("b"))
assertEquals("3", cache.get("c"))
}
@Test
fun `put does not evict non-expired entries`() {
val timeSource = TestTimeSource()
val cache = TtlCache<String, String>(ttl = 10.minutes, timeSource = timeSource)
cache.put("a", "1")
timeSource += 5.minutes
cache.put("b", "2")
assertEquals("1", cache.get("a"))
assertEquals("2", cache.get("b"))
}
@Test
fun `concurrent put and get do not throw`() = runTest {
val cache = TtlCache<Int, String>(ttl = 10.minutes)
val jobs = (1..100).map { i ->
launch {
cache.put(i, "value-$i")
cache.get(i)
cache.put(i, "updated-$i")
cache.get(i)
}
}
jobs.joinAll()
}
}

View file

@ -0,0 +1,35 @@
package org.kotlinlang.mcp.config
import io.ktor.server.config.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class ServerConfigTest {
@Test
fun `toServerConfig maps all Algolia properties`() {
val config = MapApplicationConfig(
"algolia.appId" to "test-app-id",
"algolia.apiKey" to "test-api-key",
"algolia.indexName" to "test-index",
)
val serverConfig = config.toServerConfig()
assertEquals("test-app-id", serverConfig.algoliaAppId)
assertEquals("test-api-key", serverConfig.algoliaApiKey)
assertEquals("test-index", serverConfig.algoliaIndexName)
}
@Test
fun `toServerConfig throws when required property is missing`() {
val config = MapApplicationConfig(
"algolia.appId" to "test-app-id",
)
assertFailsWith<ApplicationConfigurationException> {
config.toServerConfig()
}
}
}

View file

@ -0,0 +1,87 @@
package org.kotlinlang.mcp.content
import io.ktor.client.*
import io.ktor.client.engine.mock.*
import io.ktor.client.plugins.*
import io.ktor.http.*
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class PageFetcherTest {
private fun createFetcher(mockEngine: MockEngine): PageFetcher {
val httpClient = HttpClient(mockEngine) {
expectSuccess = true
}
return PageFetcher(httpClient)
}
@Test
fun `fetch sends GET request to provided URL`() = runTest {
val mockEngine = MockEngine { request ->
assertEquals("https://kotlinlang.org/docs/_llms/coroutines-overview.txt", request.url.toString())
assertEquals(HttpMethod.Get, request.method)
respond(
content = "# Coroutines overview",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val fetcher = createFetcher(mockEngine)
fetcher.fetch("https://kotlinlang.org/docs/_llms/coroutines-overview.txt")
}
@Test
fun `fetch returns response body as text`() = runTest {
val pageContent = "# Coroutines\n\nKotlin provides coroutines support at the language level."
val mockEngine = MockEngine {
respond(
content = pageContent,
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val fetcher = createFetcher(mockEngine)
val result = fetcher.fetch("https://kotlinlang.org/docs/_llms/coroutines-overview.txt")
assertEquals(pageContent, result)
}
@Test
fun `fetch throws ClientRequestException on 404`() = runTest {
val mockEngine = MockEngine {
respond(
content = "Not Found",
status = HttpStatusCode.NotFound,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val fetcher = createFetcher(mockEngine)
assertFailsWith<ClientRequestException> {
fetcher.fetch("https://kotlinlang.org/docs/_llms/nonexistent.txt")
}
}
@Test
fun `fetch throws ServerResponseException on 5xx`() = runTest {
val mockEngine = MockEngine {
respond(
content = "Internal Server Error",
status = HttpStatusCode.InternalServerError,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val fetcher = createFetcher(mockEngine)
assertFailsWith<ServerResponseException> {
fetcher.fetch("https://kotlinlang.org/docs/_llms/coroutines-overview.txt")
}
}
}

View file

@ -0,0 +1,91 @@
package org.kotlinlang.mcp.content
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class UrlMapperTest {
@Test
fun `top-level path maps to _llms URL`() {
assertEquals(
"https://kotlinlang.org/docs/_llms/coroutines-overview.txt",
mapPathToUrl("coroutines-overview"),
)
}
@Test
fun `nested path maps to _llms URL`() {
assertEquals(
"https://kotlinlang.org/docs/multiplatform/_llms/compose.txt",
mapPathToUrl("multiplatform/compose"),
)
}
@Test
fun `deep nested path maps to _llms URL`() {
assertEquals(
"https://kotlinlang.org/docs/a/b/_llms/c.txt",
mapPathToUrl("a/b/c"),
)
}
@Test
fun `trims leading and trailing slashes`() {
assertEquals(
"https://kotlinlang.org/docs/_llms/coroutines-overview.txt",
mapPathToUrl("/coroutines-overview/"),
)
}
@Test
fun `strips html extension`() {
assertEquals(
"https://kotlinlang.org/docs/_llms/coroutines-overview.txt",
mapPathToUrl("coroutines-overview.html"),
)
}
@Test
fun `normalizes slashes and html extension together`() {
assertEquals(
"https://kotlinlang.org/docs/multiplatform/_llms/compose.txt",
mapPathToUrl("/multiplatform/compose.html"),
)
}
@Test
fun `empty string throws IllegalArgumentException`() {
assertFailsWith<IllegalArgumentException> {
mapPathToUrl("")
}
}
@Test
fun `only slashes throws IllegalArgumentException`() {
assertFailsWith<IllegalArgumentException> {
mapPathToUrl("///")
}
}
@Test
fun `blank path throws IllegalArgumentException`() {
assertFailsWith<IllegalArgumentException> {
mapPathToUrl(" ")
}
}
@Test
fun `path traversal throws IllegalArgumentException`() {
assertFailsWith<IllegalArgumentException> {
mapPathToUrl("../../secret")
}
}
@Test
fun `path traversal in the middle throws IllegalArgumentException`() {
assertFailsWith<IllegalArgumentException> {
mapPathToUrl("multiplatform/../secret")
}
}
}

View file

@ -0,0 +1,139 @@
package org.kotlinlang.mcp.tools
import io.ktor.client.*
import io.ktor.client.engine.mock.*
import io.ktor.http.*
import io.modelcontextprotocol.kotlin.sdk.types.TextContent
import kotlinx.coroutines.test.runTest
import org.kotlinlang.mcp.cache.TtlCache
import org.kotlinlang.mcp.content.PageFetcher
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.hours
class GetKotlinlangPageTest {
private fun createTool(mockEngine: MockEngine): GetKotlinlangPage {
val httpClient = HttpClient(mockEngine) {
expectSuccess = true
}
val pageFetcher = PageFetcher(httpClient)
val cache = TtlCache<String, String>(ttl = 1.hours)
return GetKotlinlangPage(pageFetcher, cache)
}
@Test
fun `handle returns page content for valid path`() = runTest {
val pageContent = "# Coroutines\n\nKotlin provides coroutines support."
val mockEngine = MockEngine { request ->
assertEquals(
"https://kotlinlang.org/docs/_llms/coroutines-overview.txt",
request.url.toString(),
)
respond(
content = pageContent,
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val tool = createTool(mockEngine)
val result = tool.handle("coroutines-overview")
val text = (result.content.first() as TextContent).text
assertNull(result.isError)
assertEquals(pageContent, text)
}
@Test
fun `handle returns cached content on second call`() = runTest {
var callCount = 0
val mockEngine = MockEngine {
callCount++
respond(
content = "# Page content",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val tool = createTool(mockEngine)
val result1 = tool.handle("coroutines-overview")
val result2 = tool.handle("coroutines-overview")
assertEquals(1, callCount)
assertEquals(
(result1.content.first() as TextContent).text,
(result2.content.first() as TextContent).text,
)
}
@Test
fun `handle returns error with hint on 404`() = runTest {
val mockEngine = MockEngine {
respond(
content = "Not Found",
status = HttpStatusCode.NotFound,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val tool = createTool(mockEngine)
val result = tool.handle("nonexistent-page")
val text = (result.content.first() as TextContent).text
assertEquals(true, result.isError)
assertTrue(text.contains("Page not found: nonexistent-page"))
assertTrue(text.contains("search_kotlinlang"))
}
@Test
fun `handle returns error on network failure`() = runTest {
val mockEngine = MockEngine {
respond(
content = "Internal Server Error",
status = HttpStatusCode.InternalServerError,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val tool = createTool(mockEngine)
val result = tool.handle("coroutines-overview")
assertEquals(true, result.isError)
val text = (result.content.first() as TextContent).text
assertTrue(text.startsWith("Failed to fetch page:"))
}
@Test
fun `handle returns error on empty path`() = runTest {
val mockEngine = MockEngine {
respond(
content = "should not reach",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "text/plain"),
)
}
val tool = createTool(mockEngine)
val result = tool.handle("")
assertEquals(true, result.isError)
val text = (result.content.first() as TextContent).text
assertTrue(text.contains("Invalid path:"))
}
@Test
fun `handle rethrows CancellationException`() = runTest {
val mockEngine = MockEngine {
throw kotlinx.coroutines.CancellationException("cancelled")
}
val tool = createTool(mockEngine)
kotlin.test.assertFailsWith<kotlinx.coroutines.CancellationException> {
tool.handle("coroutines-overview")
}
}
}

View file

@ -0,0 +1,231 @@
package org.kotlinlang.mcp.tools
import io.ktor.client.*
import io.ktor.client.engine.mock.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import org.kotlinlang.mcp.algolia.AlgoliaClient
import org.kotlinlang.mcp.cache.TtlCache
import org.kotlinlang.mcp.config.ServerConfig
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.minutes
import kotlin.time.TestTimeSource
class SearchKotlinlangTest {
private val testConfig = ServerConfig(
algoliaAppId = "test-app-id",
algoliaApiKey = "test-api-key",
algoliaIndexName = "test-index",
)
private val json = Json { ignoreUnknownKeys = true }
private fun createSearchTool(
mockEngine: MockEngine,
timeSource: TestTimeSource = TestTimeSource(),
): SearchKotlinlang {
val httpClient = HttpClient(mockEngine) {
install(ContentNegotiation) { json(json) }
}
val algoliaClient = AlgoliaClient(testConfig, httpClient)
val cache = TtlCache<String, String>(ttl = 10.minutes, timeSource = timeSource)
return SearchKotlinlang(algoliaClient, cache)
}
private fun mockEngineWithHits(hitsJson: String): MockEngine = MockEngine {
respond(
content = """{"hits": [$hitsJson]}""",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
private fun hit(
objectID: String = "id1",
mainTitle: String? = "Title",
url: String = "/docs/test.html",
snippet: String? = "some text",
matchLevel: String = "full",
): String = buildString {
append("""{"objectID":"$objectID","url":"$url"""")
if (mainTitle != null) append(""","mainTitle":"$mainTitle"""")
if (snippet != null) {
append(""","_snippetResult":{"content":{"value":"$snippet","matchLevel":"$matchLevel"}}""")
}
append("}")
}
@Test
fun `filters out non-docs hits`() = runTest {
val engine = mockEngineWithHits(
listOf(
hit(objectID = "1", url = "/docs/coroutines.html", mainTitle = "Coroutines"),
hit(objectID = "2", url = "https://kotlinlang.org/api/core/kotlin/", mainTitle = "API"),
hit(objectID = "3", url = "/docs/flow.html", mainTitle = "Flow"),
).joinToString(",")
)
val tool = createSearchTool(engine)
val result = tool.handle("coroutines")
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
assertTrue(text.contains("Coroutines"))
assertTrue(text.contains("Flow"))
assertTrue(!text.contains("API"))
}
@Test
fun `takes only top 5 after filtering`() = runTest {
val hits = (1..10).map { i ->
hit(objectID = "id$i", url = "/docs/page$i.html", mainTitle = "Page $i", snippet = "text $i")
}
val engine = mockEngineWithHits(hits.joinToString(","))
val tool = createSearchTool(engine)
val result = tool.handle("kotlin")
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
for (i in 1..5) assertTrue(text.contains("Page $i"), "Should contain Page $i")
for (i in 6..10) assertTrue(!text.contains("Page $i"), "Should not contain Page $i")
}
@Test
fun `formats results with title path and snippet`() = runTest {
val engine = mockEngineWithHits(
hit(
objectID = "1",
url = "/docs/coroutines-overview.html",
mainTitle = "Coroutines overview",
snippet = "Kotlin provides coroutines support",
)
)
val tool = createSearchTool(engine)
val result = tool.handle("coroutines")
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
assertEquals(
"""
1. Coroutines overview [coroutines-overview]
Kotlin provides coroutines support
""".trimIndent(),
text,
)
}
@Test
fun `strips HTML tags from snippet`() = runTest {
val engine = mockEngineWithHits(
hit(snippet = "<em>coroutines</em> are <strong>great</strong>")
)
val tool = createSearchTool(engine)
val result = tool.handle("coroutines")
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
assertTrue(text.contains("coroutines are great"))
assertTrue(!text.contains("<em>"))
assertTrue(!text.contains("<strong>"))
}
@Test
fun `uses Untitled when mainTitle is null`() = runTest {
val engine = mockEngineWithHits(
hit(mainTitle = null, url = "/docs/basics.html", snippet = "some text")
)
val tool = createSearchTool(engine)
val result = tool.handle("basics")
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
assertTrue(text.contains("Untitled [basics]"))
}
@Test
fun `omits snippet line when snippetResult is null`() = runTest {
val engine = mockEngineWithHits(
hit(url = "/docs/basics.html", mainTitle = "Basics", snippet = null)
)
val tool = createSearchTool(engine)
val result = tool.handle("basics")
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
assertEquals("1. Basics [basics]", text)
}
@Test
fun `returns no results message when all hits are filtered out`() = runTest {
val engine = mockEngineWithHits(
hit(url = "https://kotlinlang.org/api/core/kotlin/", mainTitle = "API")
)
val tool = createSearchTool(engine)
val result = tool.handle("something")
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
assertNull(result.isError)
assertEquals("No results found for: something", text)
}
@Test
fun `returns isError true when Algolia fails`() = runTest {
val engine = MockEngine {
respond(
content = """{"message": "Internal server error"}""",
status = HttpStatusCode.InternalServerError,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val tool = createSearchTool(engine)
val result = tool.handle("coroutines")
assertEquals(true, result.isError)
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
assertTrue(text.startsWith("Search failed:"))
}
@Test
fun `caches result and does not call Algolia on second request`() = runTest {
var callCount = 0
val engine = MockEngine {
callCount++
respond(
content = """{"hits": [${hit(url = "/docs/test.html")}]}""",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val tool = createSearchTool(engine)
tool.handle("coroutines")
tool.handle("coroutines")
assertEquals(1, callCount)
}
@Test
fun `extracts path from nested URL`() = runTest {
val engine = mockEngineWithHits(
hit(
url = "/docs/multiplatform/compose.html",
mainTitle = "Compose",
snippet = "text",
)
)
val tool = createSearchTool(engine)
val result = tool.handle("compose")
val text = result.content.first().let { (it as io.modelcontextprotocol.kotlin.sdk.types.TextContent).text }
assertTrue(text.contains("[multiplatform/compose]"))
}
}