Kotlin SDK
Официальный Kotlin Multiplatform SDK для Model Context Protocol — JVM, WebAssembly и Native платформы
Официальный Kotlin Multiplatform SDK для Model Context Protocol предоставляет клиентские и серверные возможности для интеграции с LLM на различных платформах: JVM, WebAssembly и Native (iOS).
Возможности
Заголовок раздела «Возможности»- Создание MCP-клиентов для подключения к любым MCP-серверам
- Создание MCP-серверов с resources, prompts и tools
- Поддержка транспортов: stdio, SSE, WebSocket
- Обработка всех протокольных сообщений и событий жизненного цикла
- Multiplatform: JVM, Wasm/JS, Native (iOS)
Требования
Заголовок раздела «Требования»- Kotlin 2.2+
- JVM 11+ (для JVM-платформы)
- Ktor (клиент и/или сервер)
Установка
Заголовок раздела «Установка»repositories { mavenCentral()}
dependencies { // MCP SDK implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
// Ktor клиент (выберите движок) implementation("io.ktor:ktor-client-cio:$ktorVersion")
// Ktor сервер (для SSE/HTTP) implementation("io.ktor:ktor-server-netty:$ktorVersion")}Создание клиента
Заголовок раздела «Создание клиента»import io.modelcontextprotocol.kotlin.sdk.client.Clientimport io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransportimport io.modelcontextprotocol.kotlin.sdk.Implementation
val client = Client( clientInfo = Implementation( name = "example-client", version = "1.0.0" ))
val transport = StdioClientTransport( inputStream = processInputStream, outputStream = processOutputStream)
// Подключение к серверуclient.connect(transport)
// Список доступных ресурсовval resources = client.listResources()
// Чтение ресурсаval resourceContent = client.readResource( ReadResourceRequest(uri = "file:///example.txt"))Создание сервера
Заголовок раздела «Создание сервера»import io.modelcontextprotocol.kotlin.sdk.server.Serverimport io.modelcontextprotocol.kotlin.sdk.server.ServerOptionsimport io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransportimport io.modelcontextprotocol.kotlin.sdk.ServerCapabilities
val server = Server( serverInfo = Implementation( name = "example-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( resources = ServerCapabilities.Resources( subscribe = true, listChanged = true ) ) )) { "Этот сервер предоставляет примеры ресурсов и демонстрирует возможности MCP."}
// Добавление ресурсаserver.addResource( uri = "file:///example.txt", name = "Example Resource", description = "Пример текстового файла", mimeType = "text/plain") { request -> ReadResourceResult( contents = listOf( TextResourceContents( text = "Содержимое примера ресурса.", uri = request.uri, mimeType = "text/plain" ) ) )}
// Запуск с stdio транспортомval transport = StdioServerTransport()server.connect(transport)SSE Transport (Ktor)
Заголовок раздела «SSE Transport (Ktor)»В Application
Заголовок раздела «В Application»import io.ktor.server.application.*import io.modelcontextprotocol.kotlin.sdk.server.mcp
fun Application.module() { mcp { Server( serverInfo = Implementation( name = "example-sse-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( prompts = ServerCapabilities.Prompts(listChanged = null), resources = ServerCapabilities.Resources( subscribe = null, listChanged = null ) ) ), ) { "SSE-сервер для prompts и resources." } }}В кастомном Route
Заголовок раздела «В кастомном Route»import io.ktor.server.application.*import io.ktor.server.sse.SSEimport io.modelcontextprotocol.kotlin.sdk.server.mcp
fun Application.module() { install(SSE)
routing { route("myRoute") { mcp { Server( serverInfo = Implementation( name = "example-sse-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( prompts = ServerCapabilities.Prompts(listChanged = null), resources = ServerCapabilities.Resources( subscribe = null, listChanged = null ) ) ), ) { "Подключитесь через SSE для взаимодействия с MCP-сервером." } } } }}Примеры проектов
Заголовок раздела «Примеры проектов»| Проект | Описание |
|---|---|
| kotlin-mcp-server | Multiplatform сервер (JVM, Wasm) с различными транспортами |
| weather-stdio-server | Сервер погоды через STDIO |
| kotlin-mcp-client | Интерактивный клиент с Anthropic API |
Работа с инструментами
Заголовок раздела «Работа с инструментами»// Добавление инструментаserver.addTool( name = "calculator", description = "Выполняет математические вычисления", inputSchema = JsonSchema( type = "object", properties = mapOf( "expression" to JsonSchema(type = "string") ), required = listOf("expression") )) { arguments -> val expression = arguments["expression"]?.jsonPrimitive?.content val result = evaluateExpression(expression)
CallToolResult( content = listOf( TextContent(text = "Результат: $result") ) )}Работа с prompts
Заголовок раздела «Работа с prompts»// Добавление promptserver.addPrompt( name = "greeting", description = "Генерирует приветствие", arguments = listOf( PromptArgument( name = "name", description = "Имя для приветствия", required = true ) )) { arguments -> val name = arguments["name"]
GetPromptResult( description = "Приветствие для $name", messages = listOf( PromptMessage( role = Role.USER, content = TextContent("Привет, $name!") ) ) )}Multiplatform поддержка
Заголовок раздела «Multiplatform поддержка»kotlin { jvm()
sourceSets { jvmMain.dependencies { implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion") implementation("io.ktor:ktor-client-cio:$ktorVersion") } }}WebAssembly / JS
Заголовок раздела «WebAssembly / JS»kotlin { wasmJs { browser() }
sourceSets { wasmJsMain.dependencies { implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion") implementation("io.ktor:ktor-client-js:$ktorVersion") } }}Native (iOS)
Заголовок раздела «Native (iOS)»kotlin { iosArm64() iosSimulatorArm64()
sourceSets { iosMain.dependencies { implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion") implementation("io.ktor:ktor-client-darwin:$ktorVersion") } }}