Model Context Protocol (MCP) 入门

Model Context Protocol (MCP) 规范了 AI 应用程序与外部工具和资源交互的方式。

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

介绍视频

从这里开始,您可以概览 Model Context Protocol,了解核心概念和架构。

完整教程和源代码

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

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

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

快速入门

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

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

添加依赖并配置

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

添加依赖并配置

<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>
spring:
  ai:
    mcp:
      client:
        streamable-http:
          connections:
            weather-server:
              url: https://:8080

学习资源

实现视频

Spring AI 的 MCP 集成视频演练,涵盖服务器和客户端实现。

其他示例仓库

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

基于注解的示例

社区资源

© . This site is unofficial and not affiliated with VMware.