|
此版本仍在开发中,尚未被视为稳定版。如需最新的快照版本,请使用 Spring AI 1.1.3! |
开始使用模型上下文协议 (MCP)
模型上下文协议(MCP)标准化了 AI 应用程序与外部工具和资源的交互方式。
Spring 作为主要贡献者早期加入了 MCP 生态系统,帮助开发和维护 官方 MCP Java SDK,该 SDK 是基于 Java 的 MCP 实现的基础。 在此基础上,Spring AI 通过 Boot Starters 和注解提供 MCP 支持,使得构建 MCP 服务器和客户端变得简单。
完整教程和源代码
📖 博客教程: 将您的AI连接到一切
💻 完整源代码: MCP 天气示例仓库
本教程涵盖了使用 Spring AI 进行 MCP 开发的要点,包括高级功能和部署模式。 下面的所有代码示例均取自本教程。
快速开始
Spring AI 的注解方式是开始使用的最快途径。以下示例来自博客教程:
简单的 MCP 服务器
@Service
public class WeatherService {
@McpTool(description = "Get current temperature for a location")
public String getTemperature(
@McpToolParam(description = "City name", required = true) String city) {
return String.format("Current temperature in %s: 22°C", city);
}
}
添加依赖并进行配置:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
spring.ai.mcp.server.protocol=STREAMABLE
简单的 MCP 客户端
@Bean
public CommandLineRunner demo(ChatClient chatClient, ToolCallbackProvider mcpTools) {
return args -> {
String response = chatClient
.prompt("What's the weather like in Paris?")
.toolCallbacks(mcpTools)
.call()
.content();
System.out.println(response);
};
}
添加依赖并进行配置:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>
spring:
ai:
mcp:
client:
streamable-http:
connections:
weather-server:
url: http://localhost:8080
其他示例仓库
除了教程示例之外,Spring AI 示例 仓库还包含许多 MCP 实现。
社区资源
-
超棒的 Spring AI - 社区示例和资源
-
官方 MCP Java SDK - 由 Spring 团队开发的 Java SDK