Model Context Protocol (MCP) 入門
Model Context Protocol (MCP) 規範了 AI 應用程式與外部工具和資源互動的方式。
Spring 作為關鍵貢獻者很早就加入了 MCP 生態系統,幫助開發和維護了 官方 MCP Java SDK,該 SDK 是基於 Java 的 MCP 實現的基礎。在此貢獻的基礎上,Spring AI 透過 Boot Starter 和註解提供 MCP 支援,使得構建 MCP 伺服器和客戶端變得容易。
完整教程和原始碼
📖 部落格教程: 將您的 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 Examples 倉庫還包含大量的 MCP 實現。
社群資源
-
Awesome Spring AI - 社群示例和資源
-
官方 MCP Java SDK - 由 Spring 團隊開發的 Java SDK