Spring Boot 集成 Spring AI:实现可被大模型调用的 MCP Server
Model Context Protocol (MCP) 是一个标准化协议,用于让大语言模型 (LLM,如 GPT、Claude 等) 以结构化方式与外部工具、资源(如数据库、API、文件系统)交互。它充当 AI 模型与真实系统之间的桥梁,支持多种传输机制(如 STDIO、HTTP/SSE、Streamable-HTTP),确保跨环境灵活性。
在 Spring AI 中,MCP 通过 Boot Starters 和注解实现无缝集成:
- MCP Server:暴露工具、资源和提示,供 LLM 调用。LLM 可以发现这些工具并自动调用。
- MCP Client:AI 应用侧,用于连接 MCP Server。
- 优势:简化 AI 应用开发,支持工具发现、实时通知、进度跟踪、日志记录和采样(让服务器请求客户端的 LLM 生成内容)。
MCP 架构如下:
以下是使用 Spring Boot 集成 Spring AI 实现 MCP Server 的完整指南(基于 2025 年最新 Spring AI 版本,假设 Spring Boot 3.3+)。我们以一个天气预报工具为例:MCP Server 连接 Open-Meteo API,暴露 getTemperature 工具,大模型可以调用它获取温度数据。
1. 环境准备
- 前提:安装 Java 21+、Maven/Gradle、Spring Boot CLI(可选)。
- 创建项目:使用 Spring Initializr(https://start.spring.io/)创建 Spring Boot 项目,选择 Web 依赖。
- Group: com.example
- Artifact: mcp-server
- Dependencies: Spring Web
2. 添加 Spring AI 和 MCP Server 依赖
在 pom.xml 中添加(使用 Spring AI BOM 管理版本):
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.1</version> <!-- 最新版,检查 docs.spring.io -->
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId> <!-- 对于 WebMVC 的 Streamable-HTTP/SSE 支持 -->
</dependency>
<!-- 如果需要 WebFlux,支持:spring-ai-starter-mcp-server-webflux -->
</dependencies>
3. 配置应用属性(application.yml)
启用 MCP Server 并指定协议:
spring:
ai:
mcp:
server:
protocol: STREAMABLE # 或 SSE/STDIO,根据需求
server:
port: 8080 # MCP Server 监听端口
- 协议选择:
- STREAMABLE:Streamable-HTTP,支持双向流式通信。
- SSE:Server-Sent Events,适合实时通知。
- STDIO:本地进程通信,启用
spring.ai.mcp.server.stdio=true。
4. 定义 MCP 工具
使用注解暴露工具。创建一个天气工具类:
import org.modelcontextprotocol.annotations.McpTool;
import org.modelcontextprotocol.annotations.McpToolParam;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class WeatherTools {
private final RestTemplate restTemplate = new RestTemplate();
@McpTool(description = "Get current temperature for a location") // 工具描述,供 LLM 发现
public double getTemperature(
@McpToolParam(description = "Latitude of the location") double latitude, // 参数注解
@McpToolParam(description = "Longitude of the location") double longitude) {
String url = String.format("https://api.open-meteo.com/v1/forecast?latitude=%f&longitude=%f¤t_weather=true", latitude, longitude);
String response = restTemplate.getForObject(url, String.class);
// 解析 JSON 获取温度(简化示例,使用 JSON 库如 Jackson)
// 假设解析后返回温度
return 20.5; // 替换为实际解析逻辑
}
}
- 注解说明:
@McpTool:定义工具,自动生成 JSON Schema。@McpToolParam:描述参数,支持类型如 String、double。- 支持特殊参数如
McpSyncServerExchange用于高级功能(日志、进度通知)。
5. 注册工具(可选,自动发现)
Spring AI 会自动扫描 @Component 中的 @McpTool。如果需要动态注册:
import org.springframework.ai.mcp.server.McpSyncServer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class McpConfig {
@Bean
CommandLineRunner toolRunner(McpSyncServer mcpSyncServer) {
return args -> {
// 动态添加工具(如果不使用注解)
mcpSyncServer.addTool(/* SyncToolSpecification */);
mcpSyncServer.notifyToolsListChanged(); // 通知客户端工具变更
};
}
}
6. 实现高级功能(可选)
- 进度跟踪:在工具中发送进度通知。
import org.modelcontextprotocol.server.exchange.McpSyncServerExchange;
@McpTool(description = "Long-running task with progress")
public String longTask(McpSyncServerExchange exchange) {
exchange.progressNotification(0.5, "Processing 50%"); // 发送进度
// 任务逻辑
return "Done";
}
- 日志记录:
exchange.loggingNotification("Info log"); - 采样:请求客户端 LLM 生成内容。
exchange.createMessage(/* prompt */); // 如果客户端支持采样
7. 运行和测试 MCP Server
- 启动应用:
mvn spring-boot:run。 - MCP Server 在
/mcp端点暴露(默认)。 - 测试:使用 MCP Client 或 LLM(如 Claude)连接。
- 示例:从另一个 AI 应用(MCP Client)调用工具。
- 配置 Client(在另一个 Spring Boot 项目):
yaml spring: ai: mcp: client: sse: connections: weather-server: url: http://localhost:8080
8. 大模型调用 MCP Server
- 在 LLM 侧(如使用 Anthropic Claude 或 OpenAI),通过 MCP Client 连接 Server。
- LLM 会自动发现工具(如
getTemperature),并在提示中调用(e.g., “获取 Amsterdam 的温度” → LLM 调用工具)。 - 示例 Client 配置(在 AI Host 应用):
@Bean
ChatClient chatClient(ChatModel chatModel, SyncMcpToolCallbackProvider toolCallbackProvider) {
return ChatClient.builder(chatModel)
.defaultToolCallbacks(toolCallbackProvider.getToolCallbacks())
.build();
}
- 提示示例:”检查 Amsterdam 的天气,并写一首诗。” → LLM 调用工具获取数据,然后生成诗。
常见问题与最佳实践
- 安全性:使用 API 密钥保护工具,配置 CORS。
- 多服务器:Client 可连接多个 MCP Server,组合工具。
- 调试:启用日志
logging.level.org.springframework.ai.mcp=DEBUG。 - 版本:检查 Spring AI 最新版(1.0.1+),MCP 支持从 2025 年初引入。
- 资源:官方文档 、Baeldung 教程 、Spring 博客 。
这个实现让你的 MCP Server 成为可被大模型调用的后端服务,支持复杂 AI 工作流!如果需要完整代码仓库或扩展(如多工具、客户端示例),随时补充。