跳到主要内容
版本:2.0.1

Model Context Protocol (MCP) 入门

QWen Max 中英对照 Getting Started with MCP Getting Started with Model Context Protocol (MCP)

Model Context Protocol (MCP) 标准化了 AI 应用与外部工具和资源的交互方式。

Spring 作为关键贡献者早期加入了 MCP 生态,帮助开发并维护 官方 MCP Java SDK,该 SDK 是基于 Java 的 MCP 实现的基础。基于这一贡献,Spring AI 通过 Boot Starters 和注解提供 MCP 支持,使构建 MCP 服务器和客户端更加容易。

介绍视频​

从这里开始了解 Model Context Protocol 的入门概览,解释核心概念和架构。

完整教程与源代码​

📖 博客教程: 将你的 AI 连接到一切

💻 完整源代码: MCP Weather Example Repository

该教程涵盖了使用 Spring AI 进行 MCP 开发的基础知识,包括高级特性和部署模式。下面的所有代码示例均取自本教程。

快速开始​

最快的入门方式是使用 Spring AI 的基于注解的方法。以下示例来自博客教程:

简单 MCP Server​

@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?")
.tools(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 Examples 仓库包含许多 MCP 实现。

基于注解的示例

按用例​

天气服务:

数据集成:

Web 集成:

客户端示例:

社区资源​

参考文档​