Certainly! Below is a complete guide for creating a simple MCP (Model Context Protocol) server in Kotlin using Ktor, and packaging it with a Bash shell script to run the server.
✅ Overview
- Tech Stack: Kotlin, Ktor
- Functionality:
- Minimal TCP server that listens for incoming command strings.
- Parses the string and responds with a predefined or dynamic response.
- Packaging: Bash script to build and run the server.
🚀 Step 1: Kotlin/Ktor TCP Server
We'll create a basic TCP server (Ktor is HTTP-based, but we can use sockets for MCP-style communications).
📁 Directory Structure:
mcp-server/
├── build.gradle.kts
├── settings.gradle.kts
├── src/
│ └── main/
│ └── kotlin/
│ └── MCPServer.kt
└── run.sh
💻 1. build.gradle.kts
plugins {
kotlin("jvm") version "1.9.22"
application
}
group = "org.example"
version = "1.0"
application {
mainClass.set("MCPServerKt")
}
repositories {
mavenCentral()
}
dependencies {
// No Ktor, using low-level sockets for TCP as MCP is not HTTP.
}
📜 2. settings.gradle.kts
rootProject.name = "MCPServer"
📄 3. src/main/kotlin/MCPServer.kt
import java.net.ServerSocket
import java.net.Socket
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import kotlin.concurrent.thread
fun main() {
val PORT = 5050
println("✅ MCP Server started on port $PORT")
val serverSocket = ServerSocket(PORT)
while (true) {
val client = serverSocket.accept()
println("🔌 New client connected: ${client.inetAddress.hostAddress}")
handleClient(client)
}
}
fun handleClient(client: Socket) {
thread {
client.use {
val reader = BufferedReader(InputStreamReader(client.getInputStream()))
val writer = PrintWriter(client.getOutputStream(), true)
writer.println("Welcome to MCP Server!")
var line: String?
while (reader.readLine().also { line = it } != null) {
println("📥 Received: $line")
// Simple protocol logic: echo or respond differently
val response = when (line?.trim()?.lowercase()) {
"ping" -> "PONG"
"hello" -> "Hi there!"
"bye" -> {
writer.println("Goodbye!")
break
}
else -> "Unknown command: $line"
}
writer.println(response)
}
println("❌ Client disconnected: ${client.inetAddress.hostAddress}")
}
}
}
🐚 4. run.sh
#!/bin/bash
PROJECT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
echo "🚧 Building MCP Server..."
cd "$PROJECT_DIR"
./gradlew clean build
JAR_FILE=$(find build/libs -name "*.jar" | head -n 1)
if [[ -n "$JAR_FILE" ]]; then
echo "🚀 Running MCP Server..."
java -jar "$JAR_FILE"
else
echo "❌ Build failed: No jar file found."
exit 1
fi
🛠️ Make it executable:
chmod +x run.sh
✅ Run it!
./run.sh
You should see:
🚧 Building MCP Server...
...
🚀 Running MCP Server...
✅ MCP Server started on port 5050
Then, from another terminal (or use telnet):
telnet 127.0.0.1 5050
Type:
ping
hello
bye
✅ Example Output (Client)
Welcome to MCP Server!
ping
PONG
hello
Hi there!
bye
Goodbye!
📌 Notes
- Protocol is plain text TCP for simplicity, mimicking MCP packet flow.
- This is great for embedding inside a game protocol, text-based command client, or chat server.
- You can extend this to JSON commands, or integrate real Ktor HTTP server if you switch to REST/MCP hybrid.
Would you like a gradle wrapper included for systems without it installed?