Spring Ai超简单教程系列 - 08MCP服务端开发
在网上找了一些Spring AI相关的教程,因为官方API更新较快的原因,大部分教程的内容都已过时。所以在参照官方参考文档学习的同时,沉淀每篇文章,为同样热爱学习的你,提供参考。
本系列教程参考Spring AI官方1.1.x版本文档:https://docs.spring.io/spring-ai/reference/1.1/index.html
MCP服务端开发
在07工具调用章节介绍了本地tool注册到ChatClient中,实现大模型对话过程中可以调用匹配的工具。
MCP是Model Context Protocol模型上下文协议的缩写,可以以结构化方式让AI模型与外部工具和资源进行交互。
Java作为企业级应用开发主流语言,在MCP Server方面具备天然优势,可以把成熟业务通过MCP Tool方式,提供给Agent智能体调用,实现智能化场景下的业务闭环。
Spring AI MCP 集成
Sprng AI提供了多种MCP传输机制,可以简单理解:
- STDIO:主要用于本地调用
- SSE:支持通过网络远程调用
实战演练
使用Spring AI开发一个天气查询的MCP Server,通过Chatbox工具配置本地MCP Server地址,通过对话的方式让Chatbox工具调用天气查询的Tool。
MCP Server
添加spring-ai-starter-mcp-server-webmvc依赖:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
定义天气查询工具:
@Component
public class McpWeatherTools {
private final WebClient webClient = WebClient.builder().baseUrl("https://uapis.cn").build();
@McpTool(
name = "getCurrentWeather",
description = "根据城市名称查询当前天气信息"
)
public String getCurrentWeather(
@McpToolParam(description = "需要查询的城市名") String city
) {
log.info("调用获取天气MCP Tool");
Optional<String> result = webClient.get()
.uri(
uriBuilder -> uriBuilder
.path("/api/v1/misc/weather")
.queryParam("city", city)
.build()
)
.retrieve()
.bodyToMono(String.class)
.blockOptional();
return new WeatherService.WeatherToolCallResultConverter().convert(result, String.class);
}
}
配置文件(使用的都是默认属性值,不配置效果一样):
spring.ai.mcp.server.type=sync
spring.ai.mcp.server.annotation-scanner.enabled=true
spring.ai.mcp.server.sse-endpoint=/sse
spring.ai.mcp.server.sse-message-endpoint=/mcp/message
spring.ai.mcp.server.protocol=sse
通过SSE协议获取工具列表:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"tools": [
{
"name": "getCurrentWeather",
"title": "getCurrentWeather",
"description": "根据城市名称查询当前天气信息",
"inputSchema": {
"type": "object",
"properties": {
"arg0": {
"type": "string",
"description": "需要查询的城市名"
}
},
"required": [
"arg0"
]
},
"annotations": {
"title": "",
"readOnlyHint": false,
"destructiveHint": true,
"idempotentHint": false,
"openWorldHint": true
}
}
]
}
}
客户端调用
这里没有单独开发MCP客户端,直接使用平时大模型聊天工具Chatbox配置MCP服务端地址,工具中也可以看到getCurrentWeather:

新建对话,选择工作模式激活MCP工具:

测试
输入:
厦门今天的天气怎么样?
思考过程,可以看到过程中调用了getCurrentWeather工具:
已深度思考· The user is asking about the weather in Xiamen again. The previous two attempts failed - the first one timed out, and the next two were stopped by the user. Let me try once more. If it fails again, I should admit that I can't get the weather right now and suggest alternatives.
mcp__local_test__getCurrentWeather· 已完成
已深度思考· The query succeeded this time. Let me report the weather to the user in Chinese.
返回结果:
厦门今天天气不错:
天气:晴 ☀️
温度:28°C
风力:南风 4 级
天气晴朗温暖,适合外出活动。南风 4 级风力稍大,如果在海边或骑行的话可以留意一下。

浙公网安备 33010602011771号