MCP Kotlin入门
Kotlin中一个功能完整的模型上下文协议(MCP)服务器模板。此入门程序使用干净的生产就绪代码演示了MCP的所有主要功能。
📚 文档
- 模型上下文协议
- Kotlin SDK
- 构建MCP服务器
✨ 特性
| 类别 | 功能 | 描述 |
|---|---|---|
| 工具 | hello |
基本问候工具 |
get_weather |
具有结构化JSON输出的工具 | |
long_task |
带有进度报告的任务 | |
calculate |
算术运算 | |
echo |
回显消息 | |
| 资源 | info://about |
服务器信息 |
doc://example |
标记文档示例 | |
config://settings |
服务器配置 | |
| 提示 | greet |
各种风格的问候 |
code_review |
重点领域代码审查 |
⚠️ 已知限制
Kotlin MCP SDK(v0.8.1)有一些局限性。看 SDK_LIMITIONS.md 有关完整详细信息:
- 资源模板:SDK不支持
addResourceTemplate()参数化资源使用手动URI解析。 - 提示标题:The
addPrompt()方法不接受title现场。
🚀 快速开始
先决条件
- JDK 17+
- Gradle (或使用包装纸)
安装```bash
Clone the repository
git clone https://github.com/SamMorrowDrums/mcp-kotlin-starter.git
cd mcp-kotlin-starter
Build
./gradlew build
### 运行服务器
**stdio传输** (地方发展):```bash
./gradlew runStdio
HTTP传输 (用于远程/web部署):```bash
./gradlew runHttp
Server runs on http://localhost:3000
## 🔧 VS代码集成
该项目包括用于无缝开发的VS代码配置:
1. 在VS Code中打开项目
1. MCP配置位于 `.vscode/mcp.json`
1. 使用Gradle任务进行构建
1. 使用VS Code的MCP工具测试服务器
## 📁 项目结构```
.
├── src/main/kotlin/mcp/starter/
│ ├── Server.kt # Server setup with tools, resources, prompts
│ ├── StdioMain.kt # stdio transport entrypoint
│ └── HttpMain.kt # HTTP transport entrypoint
├── src/main/resources/
│ └── logback.xml # Logging configuration
├── .vscode/
│ └── mcp.json # MCP server configuration
├── build.gradle.kts # Gradle build file
├── settings.gradle.kts
├── server.json # MCP discovery configuration
└── README.md
🛠️ 发展```bash
Build the project
./gradlew build
Run tests
./gradlew test
Create a fat JAR
./gradlew fatJar
Clean build
./gradlew clean build
## 🔍 MCP 检查员
这 MCP 检查员 是测试和调试MCP服务器的重要开发工具。
### 运行检查器```bash
# First, build the fat JAR
./gradlew fatJar
# Then run with inspector
npx @modelcontextprotocol/inspector java -jar build/libs/mcp-kotlin-starter-1.0.0-all.jar
检查员提供什么
- 工具选项卡:列出并调用所有已注册的带有参数的工具
- 资源选项卡:浏览和阅读资源
- 提示选项卡:查看和测试提示模板
- 日志选项卡:请参阅客户端和服务器之间的JSON-RPC消息
📖 功能示例
添加工具```kotlin
server.addTool(
name = "hello",
description = "A friendly greeting tool"
) { request ->
val name = request.arguments["name"]?.jsonPrimitive?.content ?: "World"
listOf(TextContent("Hello, $name! Welcome to MCP."))
}
### 添加资源```kotlin
server.addResource(
uri = "config://settings",
name = "Server Settings",
mimeType = "application/json"
) {
ReadResourceResult(
contents = listOf(
TextResourceContents(
uri = "config://settings",
mimeType = "application/json",
text = """{"precision": 2}"""
)
)
)
}
添加提示```kotlin
server.addPrompt(
name = "greet",
description = "Generate a greeting in a specific style"
) { request ->
val name = request.arguments?.get("name") ?: "friend"
GetPromptResult(
messages = listOf(
PromptMessage(
role = Role.user,
content = TextContent("Write a greeting for $name.")
)
)
)
}
```
🔐 环境变量
| 变量 | 描述 | 默认值 |
|---|---|---|
PORT |
HTTP服务器端口 | 3000 |
🤝 贡献
欢迎投稿!请确保您的更改与其他语言初学者保持功能对等。
📄 许可证
MIT许可证-请参阅 许可证 了解详情。
