kotlin-mcp-server-generator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kotlin MCP Server Project Generator

Kotlin MCP服务器项目生成器

Generate a complete, production-ready Model Context Protocol (MCP) server project in Kotlin.
生成一个完整的、可用于生产环境的Kotlin版Model Context Protocol(MCP)服务器项目。

Project Requirements

项目要求

You will create a Kotlin MCP server with:
  1. Project Structure: Gradle-based Kotlin project layout
  2. Dependencies: Official MCP SDK, Ktor, and kotlinx libraries
  3. Server Setup: Configured MCP server with transports
  4. Tools: At least 2-3 useful tools with typed inputs/outputs
  5. Error Handling: Proper exception handling and validation
  6. Documentation: README with setup and usage instructions
  7. Testing: Basic test structure with coroutines
你将创建一个满足以下要求的Kotlin MCP服务器:
  1. 项目结构:基于Gradle的Kotlin项目布局
  2. 依赖项:官方MCP SDK、Ktor及kotlinx类库
  3. 服务器配置:已配置传输层的MCP服务器
  4. 工具实现:至少2-3个带有类型化输入/输出的实用工具
  5. 错误处理:完善的异常处理与参数校验
  6. 文档说明:包含搭建和使用指南的README文档
  7. 测试结构:基于协程的基础测试框架

Template Structure

项目模板结构

myserver/
├── build.gradle.kts
├── settings.gradle.kts
├── gradle.properties
├── src/
│   ├── main/
│   │   └── kotlin/
│   │       └── com/example/myserver/
│   │           ├── Main.kt
│   │           ├── Server.kt
│   │           ├── config/
│   │           │   └── Config.kt
│   │           └── tools/
│   │               ├── Tool1.kt
│   │               └── Tool2.kt
│   └── test/
│       └── kotlin/
│           └── com/example/myserver/
│               └── ServerTest.kt
└── README.md
myserver/
├── build.gradle.kts
├── settings.gradle.kts
├── gradle.properties
├── src/
│   ├── main/
│   │   └── kotlin/
│   │       └── com/example/myserver/
│   │           ├── Main.kt
│   │           ├── Server.kt
│   │           ├── config/
│   │           │   └── Config.kt
│   │           └── tools/
│   │               ├── Tool1.kt
│   │               └── Tool2.kt
│   └── test/
│       └── kotlin/
│           └── com/example/myserver/
│               └── ServerTest.kt
└── README.md

build.gradle.kts Template

build.gradle.kts模板

kotlin
plugins {
    kotlin("jvm") version "2.1.0"
    kotlin("plugin.serialization") version "2.1.0"
    application
}

group = "com.example"
version = "1.0.0"

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.modelcontextprotocol:kotlin-sdk:0.7.2")
    
    // Ktor for transports
    implementation("io.ktor:ktor-server-netty:3.0.0")
    implementation("io.ktor:ktor-client-cio:3.0.0")
    
    // Serialization
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
    
    // Coroutines
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
    
    // Logging
    implementation("io.github.oshai:kotlin-logging-jvm:7.0.0")
    implementation("ch.qos.logback:logback-classic:1.5.12")
    
    // Testing
    testImplementation(kotlin("test"))
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
}

application {
    mainClass.set("com.example.myserver.MainKt")
}

tasks.test {
    useJUnitPlatform()
}

kotlin {
    jvmToolchain(17)
}
kotlin
plugins {
    kotlin("jvm") version "2.1.0"
    kotlin("plugin.serialization") version "2.1.0"
    application
}

group = "com.example"
version = "1.0.0"

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.modelcontextprotocol:kotlin-sdk:0.7.2")
    
    // Ktor for transports
    implementation("io.ktor:ktor-server-netty:3.0.0")
    implementation("io.ktor:ktor-client-cio:3.0.0")
    
    // Serialization
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
    
    // Coroutines
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
    
    // Logging
    implementation("io.github.oshai:kotlin-logging-jvm:7.0.0")
    implementation("ch.qos.logback:logback-classic:1.5.12")
    
    // Testing
    testImplementation(kotlin("test"))
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
}

application {
    mainClass.set("com.example.myserver.MainKt")
}

tasks.test {
    useJUnitPlatform()
}

kotlin {
    jvmToolchain(17)
}

settings.gradle.kts Template

settings.gradle.kts模板

kotlin
rootProject.name = "{{PROJECT_NAME}}"
kotlin
rootProject.name = "{{PROJECT_NAME}}"

Main.kt Template

Main.kt模板

kotlin
package com.example.myserver

import io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransport
import kotlinx.coroutines.runBlocking
import io.github.oshai.kotlinlogging.KotlinLogging

private val logger = KotlinLogging.logger {}

fun main() = runBlocking {
    logger.info { "Starting MCP server..." }
    
    val config = loadConfig()
    val server = createServer(config)
    
    // Use stdio transport
    val transport = StdioServerTransport()
    
    logger.info { "Server '${config.name}' v${config.version} ready" }
    server.connect(transport)
}
kotlin
package com.example.myserver

import io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransport
import kotlinx.coroutines.runBlocking
import io.github.oshai.kotlinlogging.KotlinLogging

private val logger = KotlinLogging.logger {}

fun main() = runBlocking {
    logger.info { "Starting MCP server..." }
    
    val config = loadConfig()
    val server = createServer(config)
    
    // Use stdio transport
    val transport = StdioServerTransport()
    
    logger.info { "Server '${config.name}' v${config.version} ready" }
    server.connect(transport)
}

Server.kt Template

Server.kt模板

kotlin
package com.example.myserver

import io.modelcontextprotocol.kotlin.sdk.server.Server
import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.ServerCapabilities
import com.example.myserver.tools.registerTools

fun createServer(config: Config): Server {
    val server = Server(
        serverInfo = Implementation(
            name = config.name,
            version = config.version
        ),
        options = ServerOptions(
            capabilities = ServerCapabilities(
                tools = ServerCapabilities.Tools(),
                resources = ServerCapabilities.Resources(
                    subscribe = true,
                    listChanged = true
                ),
                prompts = ServerCapabilities.Prompts(listChanged = true)
            )
        )
    ) {
        config.description
    }
    
    // Register all tools
    server.registerTools()
    
    return server
}
kotlin
package com.example.myserver

import io.modelcontextprotocol.kotlin.sdk.server.Server
import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.ServerCapabilities
import com.example.myserver.tools.registerTools

fun createServer(config: Config): Server {
    val server = Server(
        serverInfo = Implementation(
            name = config.name,
            version = config.version
        ),
        options = ServerOptions(
            capabilities = ServerCapabilities(
                tools = ServerCapabilities.Tools(),
                resources = ServerCapabilities.Resources(
                    subscribe = true,
                    listChanged = true
                ),
                prompts = ServerCapabilities.Prompts(listChanged = true)
            )
        )
    ) {
        config.description
    }
    
    // Register all tools
    server.registerTools()
    
    return server
}

Config.kt Template

Config.kt模板

kotlin
package com.example.myserver.config

import kotlinx.serialization.Serializable

@Serializable
data class Config(
    val name: String = "{{PROJECT_NAME}}",
    val version: String = "1.0.0",
    val description: String = "{{PROJECT_DESCRIPTION}}"
)

fun loadConfig(): Config {
    return Config(
        name = System.getenv("SERVER_NAME") ?: "{{PROJECT_NAME}}",
        version = System.getenv("VERSION") ?: "1.0.0",
        description = System.getenv("DESCRIPTION") ?: "{{PROJECT_DESCRIPTION}}"
    )
}
kotlin
package com.example.myserver.config

import kotlinx.serialization.Serializable

@Serializable
data class Config(
    val name: String = "{{PROJECT_NAME}}",
    val version: String = "1.0.0",
    val description: String = "{{PROJECT_DESCRIPTION}}"
)

fun loadConfig(): Config {
    return Config(
        name = System.getenv("SERVER_NAME") ?: "{{PROJECT_NAME}}",
        version = System.getenv("VERSION") ?: "1.0.0",
        description = System.getenv("DESCRIPTION") ?: "{{PROJECT_DESCRIPTION}}"
    )
}

Tool1.kt Template

Tool1.kt模板

kotlin
package com.example.myserver.tools

import io.modelcontextprotocol.kotlin.sdk.server.Server
import io.modelcontextprotocol.kotlin.sdk.CallToolRequest
import io.modelcontextprotocol.kotlin.sdk.CallToolResult
import io.modelcontextprotocol.kotlin.sdk.TextContent
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject
import kotlinx.serialization.json.putJsonArray

fun Server.registerTool1() {
    addTool(
        name = "tool1",
        description = "Description of what tool1 does",
        inputSchema = buildJsonObject {
            put("type", "object")
            putJsonObject("properties") {
                putJsonObject("param1") {
                    put("type", "string")
                    put("description", "First parameter")
                }
                putJsonObject("param2") {
                    put("type", "integer")
                    put("description", "Optional second parameter")
                }
            }
            putJsonArray("required") {
                add("param1")
            }
        }
    ) { request: CallToolRequest ->
        // Extract and validate parameters
        val param1 = request.params.arguments["param1"] as? String
            ?: throw IllegalArgumentException("param1 is required")
        val param2 = (request.params.arguments["param2"] as? Number)?.toInt() ?: 0
        
        // Perform tool logic
        val result = performTool1Logic(param1, param2)
        
        CallToolResult(
            content = listOf(
                TextContent(text = result)
            )
        )
    }
}

private fun performTool1Logic(param1: String, param2: Int): String {
    // Implement tool logic here
    return "Processed: $param1 with value $param2"
}
kotlin
package com.example.myserver.tools

import io.modelcontextprotocol.kotlin.sdk.server.Server
import io.modelcontextprotocol.kotlin.sdk.CallToolRequest
import io.modelcontextprotocol.kotlin.sdk.CallToolResult
import io.modelcontextprotocol.kotlin.sdk.TextContent
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject
import kotlinx.serialization.json.putJsonArray

fun Server.registerTool1() {
    addTool(
        name = "tool1",
        description = "Description of what tool1 does",
        inputSchema = buildJsonObject {
            put("type", "object")
            putJsonObject("properties") {
                putJsonObject("param1") {
                    put("type", "string")
                    put("description", "First parameter")
                }
                putJsonObject("param2") {
                    put("type", "integer")
                    put("description", "Optional second parameter")
                }
            }
            putJsonArray("required") {
                add("param1")
            }
        }
    ) { request: CallToolRequest ->
        // Extract and validate parameters
        val param1 = request.params.arguments["param1"] as? String
            ?: throw IllegalArgumentException("param1 is required")
        val param2 = (request.params.arguments["param2"] as? Number)?.toInt() ?: 0
        
        // Perform tool logic
        val result = performTool1Logic(param1, param2)
        
        CallToolResult(
            content = listOf(
                TextContent(text = result)
            )
        )
    }
}

private fun performTool1Logic(param1: String, param2: Int): String {
    // Implement tool logic here
    return "Processed: $param1 with value $param2"
}

tools/ToolRegistry.kt Template

tools/ToolRegistry.kt模板

kotlin
package com.example.myserver.tools

import io.modelcontextprotocol.kotlin.sdk.server.Server

fun Server.registerTools() {
    registerTool1()
    registerTool2()
    // Register additional tools here
}
kotlin
package com.example.myserver.tools

import io.modelcontextprotocol.kotlin.sdk.server.Server

fun Server.registerTools() {
    registerTool1()
    registerTool2()
    // Register additional tools here
}

ServerTest.kt Template

ServerTest.kt模板

kotlin
package com.example.myserver

import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse

class ServerTest {
    
    @Test
    fun `test server creation`() = runTest {
        val config = Config(
            name = "test-server",
            version = "1.0.0",
            description = "Test server"
        )
        
        val server = createServer(config)
        
        assertEquals("test-server", server.serverInfo.name)
        assertEquals("1.0.0", server.serverInfo.version)
    }
    
    @Test
    fun `test tool1 execution`() = runTest {
        val config = Config()
        val server = createServer(config)
        
        // Test tool execution
        // Note: You'll need to implement proper testing utilities
        // for calling tools in the server
    }
}
kotlin
package com.example.myserver

import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse

class ServerTest {
    
    @Test
    fun `test server creation`() = runTest {
        val config = Config(
            name = "test-server",
            version = "1.0.0",
            description = "Test server"
        )
        
        val server = createServer(config)
        
        assertEquals("test-server", server.serverInfo.name)
        assertEquals("1.0.0", server.serverInfo.version)
    }
    
    @Test
    fun `test tool1 execution`() = runTest {
        val config = Config()
        val server = createServer(config)
        
        // Test tool execution
        // Note: You'll need to implement proper testing utilities
        // for calling tools in the server
    }
}

README.md Template

README.md模板

markdown
undefined
markdown
undefined

{{PROJECT_NAME}}

{{PROJECT_NAME}}

A Model Context Protocol (MCP) server built with Kotlin.
基于Kotlin构建的Model Context Protocol(MCP)服务器。

Description

项目描述

{{PROJECT_DESCRIPTION}}
{{PROJECT_DESCRIPTION}}

Requirements

环境要求

  • Java 17 or higher
  • Kotlin 2.1.0
  • Java 17或更高版本
  • Kotlin 2.1.0

Installation

安装步骤

Build the project:
```bash ./gradlew build ```
构建项目:
bash
./gradlew build

Usage

使用方法

Run the server with stdio transport:
```bash ./gradlew run ```
Or build and run the jar:
```bash ./gradlew installDist ./build/install/{{PROJECT_NAME}}/bin/{{PROJECT_NAME}} ```
通过标准输入输出传输层启动服务器:
bash
./gradlew run
或构建并运行Jar包:
bash
./gradlew installDist
./build/install/{{PROJECT_NAME}}/bin/{{PROJECT_NAME}}

Configuration

配置方式

Configure via environment variables:
  • SERVER_NAME
    : Server name (default: "{{PROJECT_NAME}}")
  • VERSION
    : Server version (default: "1.0.0")
  • DESCRIPTION
    : Server description
通过环境变量进行配置:
  • SERVER_NAME
    : 服务器名称(默认值:"{{PROJECT_NAME}}")
  • VERSION
    : 服务器版本(默认值:"1.0.0")
  • DESCRIPTION
    : 服务器描述信息

Available Tools

可用工具

tool1

tool1

{{TOOL1_DESCRIPTION}}
Input:
  • param1
    (string, required): First parameter
  • param2
    (integer, optional): Second parameter
Output:
  • Text result of the operation
{{TOOL1_DESCRIPTION}}
输入参数:
  • param1
    (字符串,必填):第一个参数
  • param2
    (整数,可选):第二个参数
输出结果:
  • 操作处理后的文本结果

Development

开发指南

Run tests:
```bash ./gradlew test ```
Build:
```bash ./gradlew build ```
Run with auto-reload (development):
```bash ./gradlew run --continuous ```
运行测试:
bash
./gradlew test
构建项目:
bash
./gradlew build
自动重载模式运行(开发环境):
bash
./gradlew run --continuous

Multiplatform

多平台支持

This project uses Kotlin Multiplatform and can target JVM, Wasm, and iOS. See
build.gradle.kts
for platform configuration.
本项目采用Kotlin Multiplatform技术,可支持JVM、Wasm和iOS平台。具体平台配置请查看
build.gradle.kts
文件。

License

许可证

MIT
undefined
MIT
undefined

Generation Instructions

生成说明

When generating a Kotlin MCP server:
  1. Gradle Setup: Create proper
    build.gradle.kts
    with all dependencies
  2. Package Structure: Follow Kotlin package conventions
  3. Type Safety: Use data classes and kotlinx.serialization
  4. Coroutines: All operations should be suspending functions
  5. Error Handling: Use Kotlin exceptions and validation
  6. JSON Schemas: Use
    buildJsonObject
    for tool schemas
  7. Testing: Include coroutine test utilities
  8. Logging: Use kotlin-logging for structured logging
  9. Configuration: Use data classes and environment variables
  10. Documentation: KDoc comments for public APIs
生成Kotlin MCP服务器时需遵循以下规范:
  1. Gradle配置:创建包含所有依赖的完整
    build.gradle.kts
    文件
  2. 包结构:遵循Kotlin包命名规范
  3. 类型安全:使用数据类和kotlinx.serialization
  4. 协程支持:所有操作均使用挂起函数
  5. 错误处理:使用Kotlin异常机制和参数校验
  6. JSON Schema:使用
    buildJsonObject
    定义工具Schema
  7. 测试框架:集成kotlinx-coroutines-test测试工具
  8. 日志记录:使用kotlin-logging实现结构化日志
  9. 配置管理:使用数据类和环境变量管理配置
  10. API文档:为公共API添加KDoc注释

Best Practices

最佳实践

  • Use suspending functions for all async operations
  • Leverage Kotlin's null safety and type system
  • Use data classes for structured data
  • Apply kotlinx.serialization for JSON handling
  • Use sealed classes for result types
  • Implement proper error handling with Result/Either patterns
  • Write tests using kotlinx-coroutines-test
  • Use dependency injection for testability
  • Follow Kotlin coding conventions
  • Use meaningful names and KDoc comments
  • 所有异步操作使用挂起函数
  • 充分利用Kotlin的空安全和类型系统
  • 使用数据类处理结构化数据
  • 基于kotlinx.serialization处理JSON
  • 使用密封类定义结果类型
  • 基于Result/Either模式实现完善的错误处理
  • 使用kotlinx-coroutines-test编写测试用例
  • 依赖注入提升可测试性
  • 遵循Kotlin编码规范
  • 使用有意义的命名和KDoc注释

Transport Options

传输层选项

Stdio Transport

标准输入输出传输层

kotlin
val transport = StdioServerTransport()
server.connect(transport)
kotlin
val transport = StdioServerTransport()
server.connect(transport)

SSE Transport (Ktor)

SSE传输层(基于Ktor)

kotlin
embeddedServer(Netty, port = 8080) {
    mcp {
        Server(/*...*/) { "Description" }
    }
}.start(wait = true)
kotlin
embeddedServer(Netty, port = 8080) {
    mcp {
        Server(/*...*/) { "Description" }
    }
}.start(wait = true)

Multiplatform Configuration

多平台配置

For multiplatform projects, add to
build.gradle.kts
:
kotlin
kotlin {
    jvm()
    js(IR) { nodejs() }
    wasmJs()
    
    sourceSets {
        commonMain.dependencies {
            implementation("io.modelcontextprotocol:kotlin-sdk:0.7.2")
        }
    }
}
如需支持多平台项目,在
build.gradle.kts
中添加以下配置:
kotlin
kotlin {
    jvm()
    js(IR) { nodejs() }
    wasmJs()
    
    sourceSets {
        commonMain.dependencies {
            implementation("io.modelcontextprotocol:kotlin-sdk:0.7.2")
        }
    }
}