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

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

Spring 早期作为关键贡献者加入了 MCP 生态系统,协助开发和维护官方 MCP Java SDK 的基础,该 SDK 是基于 Java 的 MCP 实现的基础。 基于这一贡献,Spring AI 通过启动Starters和注释提供 MCP 支持,使构建 MCP 服务器和客户端变得轻松。spring-doc.cadn.net.cn

介绍视频

从这里开始,了解模型上下文协议的入门概述,解释核心概念和架构。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