概述
此示例展示了如何利用Spring AI的模型上下文协议(MCP)功能在Claude AI中调用外部工具。
核心功能
MyTool.getWeather: 返回任意天气信息的工具方法 McpConfig.myTools: 将MyTool注册为ToolCallbackProvider
执行方法
- 运行Spring Boot应用程序
./gradlew bootRun- 运行Claude桌面应用程序
- 在Claude Desktop设置中添加MCP服务器
{
"mcpServers": {
"spring-ai-mcp-weather": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:8080/mcp", "--allow-http"]
}
}
}- 重启 Claude Desktop
- 开始与Claude AI对话
- 例:“今天首尔的天气怎么样?”
提交日志
- 使用Spring Initializr创建项目
- 模型上下文协议服务器 - Spring Web
- 将Spring AI版本更改为1.1.0-M1
- 当前1.0.3版本不支持Streamable HTTP
// build.gradle.kts
extra["springAiVersion"] = "1.1.0-M1"- application.yml 配置
#application.yml
spring:
ai:
mcp:
server:
protocol: STREAMABLE
enabled: true- 工具编写
//MyTool.kt
class MyTool {
private val weathers = arrayOf("Sunny","Rainy","Cloudy")
@Tool
fun getWeather(location:String) = weathers.random()
}- 将Tool注册为Bean
@Configuration
class McpConfig {
@Bean
fun myTools(): ToolCallbackProvider = MethodToolCallbackProvider.builder().toolObjects(MyTool()).build()
}- 修改claude_desktop_config.json
{
"mcpServers": {
"spring-ai-mcp-weather": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:8080/mcp", "--allow-http"]
}
}
}
- SpringBoot运行后重启Claude Desktop
