springAI代码
mcp server
@Service
public class WeatherService {
@Tool(name = "getWeather", description = "根据城市名称获取天气预报信息")
public String getWeather(@ToolParam(description = "城市") String cityName) {
return cityName + "天气阳光明媚~";
}
}
Toolconfig
@Component
public class ToolConfig {
@Bean
public ToolCallbackProvider weatherTools(WeatherService weatherService) {
return MethodToolCallbackProvider.builder()
.toolObjects(weatherService)
.build();
}
}
配置
spring:
ai:
mcp:
server:
name: my-business-mcp-server
version: 1.0.0
# 启用 Streamable HTTP 协议
# streamable-http:
# enabled: true
# endpoint: /mcp
# 如果也想兼容老客户端,可以顺便开启 SSE
sse:
enabled: true
endpoint: /sse
调试
第一步:拿到新的 Session ID
刷新你的浏览器 http://localhost:8004/sse,在 EventStream 里复制最新的 sessionId(假设是 abc-123)。
第二步:发送初始化请求(必须发!)
curl -X POST "http://localhost:8004/mcp/message?sessionId=abc-123" -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"curl-test\",\"version\":\"1.0.0\"}}}"
(这个命令应该很快就会返回一个包含协议版本的 JSON)
第三步:发送确认通知(必须发!)
curl -X POST "http://localhost:8004/mcp/message?sessionId=abc-123" -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}"
(这个命令会返回 HTTP 200,但可能没有内容)
第四步:正式调用天气工具
curl -X POST "http://localhost:8004/mcp/message?sessionId=abc-123" -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"id\":\"2\",\"method\":\"tools/call\",\"params\":{\"name\":\"getWeather\",\"arguments\":{\"cityName\":\"北京\"}}}"
就可以收到结果了,这个是针对相同sessionID得
建议使用人家封装好的工具省的自己搞