了解 Model Context Protocol (MCP)

模型上下文协议(MCP)规范了人工智能应用与外部工具和资源的交互。spring-doc.cadn.net.cn

Spring早早地加入了MCP生态系统的贡献者行列,作为关键参与者,帮助制定并维护了t="C0">官方的MCP Java SDK,这是基于Java的MCP实现的基础架构。 在这一贡献的基础上,Spring AI通过启动脚本和注解的方式,为MCP提供了支持,使得构建MCP服务器和客户端变得更加容易。spring-doc.cadn.net.cn

引言视频

请开始此处,为模型上下文协议(Model Context Protocol, MCP)提供一个简要介绍,解释其核心概念和架构。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客户端

这是一个简单的MCP(消息客户端协议)客户端。spring-doc.cadn.net.cn

简单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