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.