此版本仍在开发中,尚未被视为稳定版。如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

开始使用模型上下文协议 (MCP)

模型上下文协议(MCP)标准化了 AI 应用程序与外部工具和资源的交互方式。spring-doc.cadn.net.cn

Spring 作为主要贡献者早期加入了 MCP 生态系统,帮助开发和维护 官方 MCP Java SDK,该 SDK 是基于 Java 的 MCP 实现的基础。 在此基础上,Spring AI 通过 Boot Starters 和注解提供 MCP 支持,使得构建 MCP 服务器和客户端变得简单。spring-doc.cadn.net.cn

介绍视频

从 Model Context Protocol 的介绍概述开始,解释核心概念和架构。spring-doc.cadn.net.cn

完整教程和源代码

本教程涵盖了使用 Spring AI 进行 MCP 开发的要点,包括高级功能和部署模式。 下面的所有代码示例均取自本教程。spring-doc.cadn.net.cn

快速开始

Spring AI 的注解方式是开始使用的最快途径。以下示例来自博客教程:spring-doc.cadn.net.cn

简单的 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);
    }
}

添加依赖并进行配置:spring-doc.cadn.net.cn

<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);
    };
}

添加依赖并进行配置:spring-doc.cadn.net.cn

<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-doc.cadn.net.cn