模型上下文协议(MCP)入门
模型上下文协议(MCP)标准化了人工智能应用与外部工具和资源的交互方式。
Spring 早期作为关键贡献者加入了 MCP 生态系统,协助开发和维护官方 MCP Java SDK 的基础,该 SDK 是基于 Java 的 MCP 实现的基础。 基于这一贡献,Spring AI 通过启动Starters和注释提供 MCP 支持,使构建 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 实现。
社区资源
-
Awesome Spring AI - 社区示例与资源
-
官方MCP Java SDK - 由Spring团队开发的Java SDK