Spring AI 2.0与MCP协议:Java开发者集成AI能力的实战指南
如果你是一名Java开发者,最近可能已经感受到了AI技术带来的冲击:大模型不再是遥不可及的实验室产品,而是正在快速渗透到企业级应用开发中。但问题也随之而来——如何将现有的Java技术栈与AI能力无缝集成?如何避免重复造轮子,快速构建具备智能能力的应用?
这正是Spring AI 2.0要解决的核心问题。作为Spring生态在AI领域的重要布局,Spring AI 2.0不仅提供了与大模型交互的标准API,更重要的是引入了MCP(Model Context Protocol)这一革命性协议,让Java开发者能够以"开箱即用"的方式集成各种AI工具和能力。
1. 为什么Spring AI 2.0值得每个Java开发者关注
传统AI应用开发面临的最大痛点就是"重复造轮子"。每个项目都需要从零开始对接各种API、处理数据格式转换、实现工具调用逻辑。而Spring AI 2.0通过MCP协议彻底改变了这一现状。
MCP可以理解为AI世界的"USB标准协议"。它定义了一套标准化的接口规范,让不同的AI工具和服务能够即插即用。无论是地图服务、代码仓库操作、数据库查询还是其他第三方服务,只要遵循MCP协议,就能被任何支持MCP的AI应用直接调用。
这种设计带来的直接好处是:
- 降低开发门槛 :无需深入理解每个工具的具体API细节
- 提高代码复用性 :一次开发的MCP服务可以被多个AI应用共享使用
- 标准化交互流程 :统一的工具发现、调用和错误处理机制
2. MCP协议的核心概念与架构解析
2.1 MCP的基本工作原理
MCP协议的核心思想是将AI应用(客户端)与具体的能力服务(服务端)解耦。整个架构包含三个关键角色:
- MCP客户端 :通常是AI应用本身,如基于Spring AI构建的智能体
- MCP服务端 :提供具体能力的服务,如天气查询、地图服务、代码仓库操作等
- MCP协议 :定义客户端与服务端之间的通信规范
工作流程如下:
- 客户端启动时发现可用的MCP服务
- 客户端获取服务端提供的工具列表和参数定义
- 用户提问时,AI模型判断需要调用哪些工具
- 客户端通过MCP协议调用相应工具并获取结果
- 客户端将工具返回的结果整合到最终回答中
2.2 MCP的两种通信模式
Spring AI支持两种MCP通信模式,适应不同的部署场景:
stdio模式 (标准输入输出):
- 服务端作为子进程被客户端启动
- 通过标准输入输出流进行通信
- 适合本地开发和小型部署场景
SSE模式 (Server-Sent Events):
- 服务端作为独立的HTTP服务运行
- 客户端通过HTTP请求调用远程服务
- 适合生产环境和微服务架构
3. 环境准备与项目搭建
3.1 基础环境要求
开始之前,确保你的开发环境满足以下要求:
- Java 17或更高版本 :Spring AI 2.0需要Java 17支持
- Maven 3.6+或Gradle 7.x :构建工具
- Spring Boot 3.2+ :基础框架
- IDE推荐 :IntelliJ IDEA或VS Code with Java插件
3.2 创建Spring Boot项目
使用Spring Initializr快速创建项目基础结构:
# 使用curl创建项目
curl https://start.spring.io/starter.zip \
-d dependencies=webflux,ai \
-d type=maven-project \
-d language=java \
-d bootVersion=3.2.0 \
-d baseDir=spring-ai-mcp-demo \
-d groupId=com.example \
-d artifactId=ai-demo \
-o spring-ai-mcp-demo.zip
# 解压并进入项目目录
unzip spring-ai-mcp-demo.zip
cd spring-ai-mcp-demo
或者直接在IDE中使用Spring Initializr创建包含WebFlux和Spring AI依赖的项目。
3.3 添加MCP相关依赖
在 pom.xml 中添加Spring AI MCP依赖:
<dependencies>
<!-- Spring AI 核心依赖 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0-M6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- MCP客户端依赖 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId>
</dependency>
<!-- WebFlux用于SSE模式 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
4. 构建你的第一个MCP服务端
4.1 基于stdio的天气查询服务
我们先创建一个简单的天气查询MCP服务端,使用stdio通信模式。
创建服务端项目结构 :
mkdir mcp-weather-server
cd mcp-weather-server
添加MCP服务端依赖 (pom.xml):
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId>
<version>1.0.0-M6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
配置应用属性 (application.yml):
spring:
main:
web-application-type: none # 禁用Web应用类型
banner-mode: off # 禁用banner
ai:
mcp:
server:
stdio: true # 启用stdio模式
name: weather-server # 服务名称
version: 1.0.0 # 服务版本
实现天气查询工具 :
package com.example.weather.service;
import org.springframework.ai.tool.Tool;
import org.springframework.ai.tool.ToolParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Service
public class WeatherService {
private final WebClient webClient;
public WeatherService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder
.baseUrl("https://api.open-meteo.com/v1")
.build();
}
@Tool(description = "根据经纬度获取天气预报信息")
public String getWeatherForecast(
@ToolParameter(description = "纬度,例如:39.9042") String latitude,
@ToolParameter(description = "经度,例如:116.4074") String longitude) {
try {
String response = webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/forecast")
.queryParam("latitude", latitude)
.queryParam("longitude", longitude)
.queryParam("current", "temperature_2m,wind_speed_10m")
.queryParam("timezone", "auto")
.build())
.retrieve()
.bodyToMono(String.class)
.block();
return formatWeatherResponse(latitude, longitude, response);
} catch (Exception e) {
return "获取天气信息失败:" + e.getMessage();
}
}
@Tool(description = "根据城市名称获取空气质量信息")
public String getAirQuality(@ToolParameter(description = "城市名称") String city) {
// 模拟空气质量数据,实际项目中应调用真实API
return String.format("""
%s的空气质量信息:
- PM2.5: 35 μg/m³ (良)
- PM10: 50 μg/m³ (良)
- 空气质量指数(AQI): 65 (良)
- 主要污染物: 颗粒物(PM2.5)
""", city);
}
private String formatWeatherResponse(String lat, String lng, String apiResponse) {
// 简化处理,实际应解析JSON响应
return String.format("""
位置(纬度:%s,经度:%s)的天气信息:
%s
""", lat, lng, apiResponse);
}
}
注册工具Bean :
package com.example.weather;
import com.example.weather.service.WeatherService;
import org.springframework.ai.mcp.server.ToolCallbackProvider;
import org.springframework.ai.mcp.server.MethodToolCallbackProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class WeatherServerApplication {
public static void main(String[] args) {
SpringApplication.run(WeatherServerApplication.class, args);
}
@Bean
public ToolCallbackProvider weatherTools(WeatherService weatherService) {
return MethodToolCallbackProvider.builder()
.toolObjects(weatherService)
.build();
}
}
打包并测试服务端 :
mvn clean package -DskipTests
java -jar target/mcp-weather-server-1.0.0.jar
5. 构建MCP客户端应用
5.1 配置MCP客户端
在客户端项目的 application.yml 中配置MCP服务:
spring:
ai:
openai:
api-key: ${OPENAI_API_KEY} # 设置你的OpenAI API密钥
mcp:
client:
stdio:
servers-configuration: classpath:/mcp-servers-config.json
创建MCP服务配置文件 src/main/resources/mcp-servers-config.json :
{
"mcpServers": {
"weather": {
"command": "java",
"args": [
"-Dspring.ai.mcp.server.stdio=true",
"-Dspring.main.web-application-type=none",
"-jar",
"/path/to/your/mcp-weather-server.jar"
],
"env": {}
}
}
}
5.2 实现客户端调用逻辑
package com.example.client;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.mcp.client.ToolCallbackProvider;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class McpClientApplication {
public static void main(String[] args) {
SpringApplication.run(McpClientApplication.class, args);
}
@Bean
public CommandLineRunner demoChat(
ChatClient.Builder chatClientBuilder,
ToolCallbackProvider toolCallbackProvider,
ConfigurableApplicationContext context) {
return args -> {
var chatClient = chatClientBuilder
.defaultTools(toolCallbackProvider)
.build();
// 测试天气查询
String weatherQuery = "北京今天的天气怎么样?";
System.out.println("用户问题: " + weatherQuery);
String weatherResponse = chatClient.prompt(weatherQuery)
.call()
.content();
System.out.println("AI回答: " + weatherResponse);
System.out.println("----------------------------------------");
// 测试空气质量查询
String airQualityQuery = "上海的空气质量如何?";
System.out.println("用户问题: " + airQualityQuery);
String airQualityResponse = chatClient.prompt(airQualityQuery)
.call()
.content();
System.out.println("AI回答: " + airQualityResponse);
context.close();
};
}
}
5.3 运行完整示例
启动客户端应用:
mvn spring-boot:run -Dspring-boot.run.arguments=--OPENAI_API_KEY=your_api_key_here
如果一切正常,你将看到类似以下的输出:
用户问题: 北京今天的天气怎么样?
AI回答: 根据查询结果,北京当前天气情况如下:
温度: 15.2°C,风速: 3.5m/s,天气状况: 晴朗
用户问题: 上海的空气质量如何?
AI回答: 上海当前的空气质量指数为65,等级为良,主要污染物为PM2.5
6. 高级特性:在OpenManus中集成MCP
OpenManus是Spring AI Alibaba提供的智能体框架,可以更复杂地编排多个工具调用。下面演示如何在OpenManus中集成MCP服务。
6.1 添加OpenManus依赖
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openmanus-spring-boot-starter</artifactId>
<version>1.0.0-M6</version>
</dependency>
6.2 配置百度地图MCP服务
首先申请百度地图API密钥,然后配置MCP服务:
{
"mcpServers": {
"baidu-map": {
"command": "npx",
"args": [
"-y",
"@baidumap/mcp-server-baidu-map"
],
"env": {
"BAIDU_MAP_API_KEY": "your_baidu_map_api_key"
}
}
}
}
6.3 实现路线规划功能
package com.example.manus;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.mcp.client.ToolCallbackProvider;
import org.springframework.ai.openmanus.annotation.Agent;
import org.springframework.ai.openmanus.annotation.AgentService;
import org.springframework.beans.factory.annotation.Autowired;
@AgentService
public class RoutePlanningService {
private final ChatClient routeChatClient;
@Autowired
public RoutePlanningService(ChatModel chatModel, ToolCallbackProvider toolCallbackProvider) {
this.routeChatClient = ChatClient.builder(chatModel)
.defaultTools(toolCallbackProvider)
.defaultSystem("你是一个专业的路线规划助手,能够使用地图工具为用户规划最佳路线。")
.build();
}
@Agent(name = "routePlanner", description = "路线规划智能体")
public String planRoute(String startCity, String endCity) {
String query = String.format("规划从%s到%s的驾车路线", startCity, endCity);
return routeChatClient.prompt(query)
.call()
.content();
}
}
6.4 测试路线规划
@Bean
public CommandLineRunner testRoutePlanning(RoutePlanningService routeService) {
return args -> {
String result = routeService.planRoute("北京", "上海");
System.out.println("路线规划结果: " + result);
};
}
运行后将获得详细的路线规划信息,包括距离、预计时间和主要途径道路。
7. 常见问题与解决方案
7.1 依赖冲突问题
问题现象 :
Caused by: java.lang.IllegalStateException: Multiple tools with the same name
解决方案 : 排除冲突的自动配置类:
@SpringBootApplication(exclude = {
org.springframework.ai.autoconfigure.mcp.client.SseHttpClientTransportAutoConfiguration.class
})
public class Application {
// ...
}
7.2 MCP服务连接失败
问题现象 :
Failed to start MCP server: Connection refused
排查步骤 :
- 检查MCP服务jar路径是否正确
- 确认Java环境变量配置
- 验证服务端是否独立运行正常
解决方案 :
{
"mcpServers": {
"weather": {
"command": "java",
"args": [
"-jar",
"/absolute/path/to/mcp-weather-server.jar"
]
}
}
}
7.3 API密钥配置错误
问题现象 :
Authentication failed for API key
解决方案 : 确保环境变量正确设置:
export OPENAI_API_KEY=your_actual_key
# 或者使用application.yml配置
8. 生产环境最佳实践
8.1 安全配置
API密钥管理 :
spring:
ai:
openai:
api-key: ${AI_API_KEY} # 从环境变量读取
MCP服务认证 :
@Bean
public WebClient.Builder secureWebClientBuilder() {
return WebClient.builder()
.filter((request, next) -> {
// 添加认证头
ClientRequest filtered = ClientRequest.from(request)
.header("Authorization", "Bearer " + apiKey)
.build();
return next.exchange(filtered);
});
}
8.2 性能优化
连接池配置 :
spring:
ai:
mcp:
client:
sse:
connection-timeout: 30s
read-timeout: 60s
异步处理 :
@Async
public CompletableFuture<String> asyncWeatherQuery(String location) {
return CompletableFuture.supplyAsync(() ->
chatClient.prompt("查询" + location + "天气").call().content()
);
}
8.3 监控与日志
添加详细日志 :
@Slf4j
@Service
public class MonitoringService {
public void logToolUsage(String toolName, Duration executionTime) {
log.info("工具 {} 执行时间: {} ms", toolName, executionTime.toMillis());
}
}
健康检查 :
@Component
public class McpHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// 检查MCP服务连接状态
return Health.up().withDetail("mcp-services", "3 connected").build();
}
}
9. 实际项目应用场景
9.1 智能客服系统
结合MCP服务构建多能力客服机器人:
public class CustomerServiceAgent {
public String handleCustomerQuery(String query) {
// 自动判断需要调用哪些MCP服务
// 如:订单查询、物流跟踪、产品信息等
return chatClient.prompt(query)
.tools(orderTool, logisticsTool, productTool)
.call()
.content();
}
}
9.2 数据分析平台
集成多种数据源进行智能分析:
public class DataAnalysisService {
public String analyzeBusinessData(String requirement) {
// 调用数据库查询、图表生成、报告编写等MCP服务
return chatClient.prompt(requirement)
.tools(dbQueryTool, chartTool, reportTool)
.call()
.content();
}
}
通过本文的实战演示,你应该已经掌握了使用Spring AI 2.0和MCP协议构建智能Java应用的核心技能。关键在于理解MCP的"即插即用"理念,将复杂的能力封装成标准化的工具服务,让AI应用能够专注于业务逻辑而非技术细节。
随着AI技术的快速发展,掌握Spring AI和MCP将成为Java开发者的一项重要竞争力。建议从简单的工具服务开始,逐步构建复杂的企业级AI应用,在实际项目中不断积累经验。
更多推荐


所有评论(0)