Lzh on GitHub

MCP(模型上下文协议)入门

模型上下文协议(MCP)标准化了 AI 应用与外部工具和资源的交互方式。

模型上下文协议(MCP)标准化了 AI 应用与外部工具和资源的交互方式。

Spring 早期就加入了 MCP 生态系统,作为重要贡献者,参与开发和维护官方 MCP Java SDK,该 SDK 为基于 Java 的 MCP 实现提供了基础。在此基础上,Spring AI 通过 Boot Starter 和注解提供了 MCP 支持,使构建 MCP 服务器和客户端变得简单易行。

介绍视频

模型上下文协议(MCP)简介 - YouTube

从这里开始,观看关于模型上下文协议的入门概览,讲解核心概念和架构。

完整教程与源代码

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

💻 完整源码:MCP 天气示例仓库

本教程涵盖了使用 Spring AI 进行 MCP 开发的基本内容,包括高级功能和部署模式。下面的所有代码示例均取自本教程。

快速入门

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

简单 MCP 服务器

@Service
public class WeatherService {

    @McpTool(description = "获取某地的当前温度")
    public String getTemperature(
            @McpToolParam(description = "城市名称", required = true) String city) {
        return String.format("%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("巴黎的天气怎么样?")
            .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)集成 - YouTube

一段关于 Spring AI MCP 集成的视频讲解,涵盖了服务器端和客户端的实现。

额外示例仓库

除了教程示例之外,Spring AI 示例 仓库还包含了大量的 MCP 实现。

推荐起点

基于注解的示例

按用例

天气服务:

数据集成:

Web 集成:

客户端示例:

社区资源

参考文档