Перейти к содержимому

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.Client
import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport
import 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.Server
import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions
import io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransport
import 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)
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."
}
}
}
import io.ktor.server.application.*
import io.ktor.server.sse.SSE
import 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-serverMultiplatform сервер (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")
)
)
}
// Добавление prompt
server.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!")
)
)
)
}
build.gradle.kts
kotlin {
jvm()
sourceSets {
jvmMain.dependencies {
implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
implementation("io.ktor:ktor-client-cio:$ktorVersion")
}
}
}
kotlin {
wasmJs {
browser()
}
sourceSets {
wasmJsMain.dependencies {
implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
implementation("io.ktor:ktor-client-js:$ktorVersion")
}
}
}
kotlin {
iosArm64()
iosSimulatorArm64()
sourceSets {
iosMain.dependencies {
implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
implementation("io.ktor:ktor-client-darwin:$ktorVersion")
}
}
}