1
---
2
name: kotlin-mcp-server-generator
3
description: 'Generate a complete Kotlin MCP server project with proper structure, dependencies, and implementation using the official io.modelcontextprotocol:kotlin-sdk library.'
4
---
5
6
# Kotlin MCP Server Project Generator
7
8
Generate a complete, production-ready Model Context Protocol (MCP) server project in Kotlin.
9
10
## Project Requirements
11
12
You will create a Kotlin MCP server with:
13
14
1. **Project Structure**: Gradle-based Kotlin project layout
15
2. **Dependencies**: Official MCP SDK, Ktor, and kotlinx libraries
16
3. **Server Setup**: Configured MCP server with transports
17
4. **Tools**: At least 2-3 useful tools with typed inputs/outputs
18
5. **Error Handling**: Proper exception handling and validation
19
6. **Documentation**: README with setup and usage instructions
20
7. **Testing**: Basic test structure with coroutines
21
22
## Template Structure
23
24
```
25
myserver/
26
├── build.gradle.kts
27
├── settings.gradle.kts
28
├── gradle.properties
29
├── src/
30
│ ├── main/
31
│ │ └── kotlin/
32
│ │ └── com/example/myserver/
33
│ │ ├── Main.kt
34
│ │ ├── Server.kt
35
│ │ ├── config/
36
│ │ │ └── Config.kt
37
│ │ └── tools/
38
│ │ ├── Tool1.kt
39
│ │ └── Tool2.kt
40
│ └── test/
41
│ └── kotlin/
42
│ └── com/example/myserver/
43
│ └── ServerTest.kt
44
└── README.md
45
```
46
47
## build.gradle.kts Template
48
49
```kotlin
50
plugins {
51
kotlin("jvm") version "2.1.0"
52
kotlin("plugin.serialization") version "2.1.0"
53
application
54
}
55
56
group = "com.example"
57
version = "1.0.0"
58
59
repositories {
60
mavenCentral()
61
}
62
63
dependencies {
64
implementation("io.modelcontextprotocol:kotlin-sdk:0.7.2")
65
66
// Ktor for transports
67
implementation("io.ktor:ktor-server-netty:3.0.0")
68
implementation("io.ktor:ktor-client-cio:3.0.0")
69
70
// Serialization
71
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
72
73
// Coroutines
74
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
75
76
// Logging
77
implementation("io.github.oshai:kotlin-logging-jvm:7.0.0")
78
implementation("ch.qos.logback:logback-classic:1.5.12")
79
80
// Testing
81
testImplementation(kotlin("test"))
82
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
83
}
84
85
application {
86
mainClass.set("com.example.myserver.MainKt")
87
}
88
89
tasks.test {
90
useJUnitPlatform()
91
}
92
93
kotlin {
94
jvmToolchain(17)
95
}
96
```
97
98
## settings.gradle.kts Template
99
100
```kotlin
101
rootProject.name = "{{PROJECT_NAME}}"
102
```
103
104
## Main.kt Template
105
106
```kotlin
107
package com.example.myserver
108
109
import io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransport
110
import kotlinx.coroutines.runBlocking
111
import io.github.oshai.kotlinlogging.KotlinLogging
112
113
private val logger = KotlinLogging.logger {}
114
115
fun main() = runBlocking {
116
logger.info { "Starting MCP server..." }
117
118
val config = loadConfig()
119
val server = createServer(config)
120
121
// Use stdio transport
122
val transport = StdioServerTransport()
123
124
logger.info { "Server '${config.name}' v${config.version} ready" }
125
server.connect(transport)
126
}
127
```
128
129
## Server.kt Template
130
131
```kotlin
132
package com.example.myserver
133
134
import io.modelcontextprotocol.kotlin.sdk.server.Server
135
import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions
136
import io.modelcontextprotocol.kotlin.sdk.Implementation
137
import io.modelcontextprotocol.kotlin.sdk.ServerCapabilities
138
import com.example.myserver.tools.registerTools
139
140
fun createServer(config: Config): Server {
141
val server = Server(
142
serverInfo = Implementation(
143
name = config.name,
144
version = config.version
145
),
146
options = ServerOptions(
147
capabilities = ServerCapabilities(
148
tools = ServerCapabilities.Tools(),
149
resources = ServerCapabilities.Resources(
150
subscribe = true,
151
listChanged = true
152
),
153
prompts = ServerCapabilities.Prompts(listChanged = true)
154
)
155
)
156
) {
157
config.description
158
}
159
160
// Register all tools
161
server.registerTools()
162
163
return server
164
}
165
```
166
167
## Config.kt Template
168
169
```kotlin
170
package com.example.myserver.config
171
172
import kotlinx.serialization.Serializable
173
174
@Serializable
175
data class Config(
176
val name: String = "{{PROJECT_NAME}}",
177
val version: String = "1.0.0",
178
val description: String = "{{PROJECT_DESCRIPTION}}"
179
)
180
181
fun loadConfig(): Config {
182
return Config(
183
name = System.getenv("SERVER_NAME") ?: "{{PROJECT_NAME}}",
184
version = System.getenv("VERSION") ?: "1.0.0",
185
description = System.getenv("DESCRIPTION") ?: "{{PROJECT_DESCRIPTION}}"
186
)
187
}
188
```
189
190
## Tool1.kt Template
191
192
```kotlin
193
package com.example.myserver.tools
194
195
import io.modelcontextprotocol.kotlin.sdk.server.Server
196
import io.modelcontextprotocol.kotlin.sdk.CallToolRequest
197
import io.modelcontextprotocol.kotlin.sdk.CallToolResult
198
import io.modelcontextprotocol.kotlin.sdk.TextContent
199
import kotlinx.serialization.json.buildJsonObject
200
import kotlinx.serialization.json.put
201
import kotlinx.serialization.json.putJsonObject
202
import kotlinx.serialization.json.putJsonArray
203
204
fun Server.registerTool1() {
205
addTool(
206
name = "tool1",
207
description = "Description of what tool1 does",
208
inputSchema = buildJsonObject {
209
put("type", "object")
210
putJsonObject("properties") {
211
putJsonObject("param1") {
212
put("type", "string")
213
put("description", "First parameter")
214
}
215
putJsonObject("param2") {
216
put("type", "integer")
217
put("description", "Optional second parameter")
218
}
219
}
220
putJsonArray("required") {
221
add("param1")
222
}
223
}
224
) { request: CallToolRequest ->
225
// Extract and validate parameters
226
val param1 = request.params.arguments["param1"] as? String
227
?: throw IllegalArgumentException("param1 is required")
228
val param2 = (request.params.arguments["param2"] as? Number)?.toInt() ?: 0
229
230
// Perform tool logic
231
val result = performTool1Logic(param1, param2)
232
233
CallToolResult(
234
content = listOf(
235
TextContent(text = result)
236
)
237
)
238
}
239
}
240
241
private fun performTool1Logic(param1: String, param2: Int): String {
242
// Implement tool logic here
243
return "Processed: $param1 with value $param2"
244
}
245
```
246
247
## tools/ToolRegistry.kt Template
248
249
```kotlin
250
package com.example.myserver.tools
251
252
import io.modelcontextprotocol.kotlin.sdk.server.Server
253
254
fun Server.registerTools() {
255
registerTool1()
256
registerTool2()
257
// Register additional tools here
258
}
259
```
260
261
## ServerTest.kt Template
262
263
```kotlin
264
package com.example.myserver
265
266
import kotlinx.coroutines.test.runTest
267
import kotlin.test.Test
268
import kotlin.test.assertEquals
269
import kotlin.test.assertFalse
270
271
class ServerTest {
272
273
@Test
274
fun `test server creation`() = runTest {
275
val config = Config(
276
name = "test-server",
277
version = "1.0.0",
278
description = "Test server"
279
)
280
281
val server = createServer(config)
282
283
assertEquals("test-server", server.serverInfo.name)
284
assertEquals("1.0.0", server.serverInfo.version)
285
}
286
287
@Test
288
fun `test tool1 execution`() = runTest {
289
val config = Config()
290
val server = createServer(config)
291
292
// Test tool execution
293
// Note: You'll need to implement proper testing utilities
294
// for calling tools in the server
295
}
296
}
297
```
298
299
## README.md Template
300
301
```markdown
302
# {{PROJECT_NAME}}
303
304
A Model Context Protocol (MCP) server built with Kotlin.
305
306
## Description
307
308
{{PROJECT_DESCRIPTION}}
309
310
## Requirements
311
312
- Java 17 or higher
313
- Kotlin 2.1.0
314
315
## Installation
316
317
Build the project:
318
319
\`\`\`bash
320
./gradlew build
321
\`\`\`
322
323
## Usage
324
325
Run the server with stdio transport:
326
327
\`\`\`bash
328
./gradlew run
329
\`\`\`
330
331
Or build and run the jar:
332
333
\`\`\`bash
334
./gradlew installDist
335
./build/install/{{PROJECT_NAME}}/bin/{{PROJECT_NAME}}
336
\`\`\`
337
338
## Configuration
339
340
Configure via environment variables:
341
342
- `SERVER_NAME`: Server name (default: "{{PROJECT_NAME}}")
343
- `VERSION`: Server version (default: "1.0.0")
344
- `DESCRIPTION`: Server description
345
346
## Available Tools
347
348
### tool1
349
{{TOOL1_DESCRIPTION}}
350
351
**Input:**
352
- `param1` (string, required): First parameter
353
- `param2` (integer, optional): Second parameter
354
355
**Output:**
356
- Text result of the operation
357
358
## Development
359
360
Run tests:
361
362
\`\`\`bash
363
./gradlew test
364
\`\`\`
365
366
Build:
367
368
\`\`\`bash
369
./gradlew build
370
\`\`\`
371
372
Run with auto-reload (development):
373
374
\`\`\`bash
375
./gradlew run --continuous
376
\`\`\`
377
378
## Multiplatform
379
380
This project uses Kotlin Multiplatform and can target JVM, Wasm, and iOS.
381
See `build.gradle.kts` for platform configuration.
382
383
## License
384
385
MIT
386
```
387
388
## Generation Instructions
389
390
When generating a Kotlin MCP server:
391
392
1. **Gradle Setup**: Create proper `build.gradle.kts` with all dependencies
393
2. **Package Structure**: Follow Kotlin package conventions
394
3. **Type Safety**: Use data classes and kotlinx.serialization
395
4. **Coroutines**: All operations should be suspending functions
396
5. **Error Handling**: Use Kotlin exceptions and validation
397
6. **JSON Schemas**: Use `buildJsonObject` for tool schemas
398
7. **Testing**: Include coroutine test utilities
399
8. **Logging**: Use kotlin-logging for structured logging
400
9. **Configuration**: Use data classes and environment variables
401
10. **Documentation**: KDoc comments for public APIs
402
403
## Best Practices
404
405
- Use suspending functions for all async operations
406
- Leverage Kotlin's null safety and type system
407
- Use data classes for structured data
408
- Apply kotlinx.serialization for JSON handling
409
- Use sealed classes for result types
410
- Implement proper error handling with Result/Either patterns
411
- Write tests using kotlinx-coroutines-test
412
- Use dependency injection for testability
413
- Follow Kotlin coding conventions
414
- Use meaningful names and KDoc comments
415
416
## Transport Options
417
418
### Stdio Transport
419
```kotlin
420
val transport = StdioServerTransport()
421
server.connect(transport)
422
```
423
424
### SSE Transport (Ktor)
425
```kotlin
426
embeddedServer(Netty, port = 8080) {
427
mcp {
428
Server(/*...*/) { "Description" }
429
}
430
}.start(wait = true)
431
```
432
433
## Multiplatform Configuration
434
435
For multiplatform projects, add to `build.gradle.kts`:
436
437
```kotlin
438
kotlin {
439
jvm()
440
js(IR) { nodejs() }
441
wasmJs()
442
443
sourceSets {
444
commonMain.dependencies {
445
implementation("io.modelcontextprotocol:kotlin-sdk:0.7.2")
446
}
447
}
448
}
449
```
450