了解 Model Context Protocol (MCP)
模型上下文协议(MCP)规范了人工智能应用与外部工具和资源的交互。
Spring早早地加入了MCP生态系统的贡献者行列,作为关键参与者,帮助制定并维护了t="C0">官方的MCP Java SDK,这是基于Java的MCP实现的基础架构。 在这一贡献的基础上,Spring AI通过启动脚本和注解的方式,为MCP提供了支持,使得构建MCP服务器和客户端变得更加容易。
完整教程及源代码
📖 Blog Tutorial: 连接您的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客户端
这是一个简单的MCP(消息客户端协议)客户端。
简单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
Additional Examples 仓库
超越教程示例,Spring AI示例存储库包含众多MCP实现。
社区资源
-
Awesome Spring AI(社区示例和资源) - Community examples and resources
-
官方MCP Java SDK - 由Spring团队开发的Java SDK