MCP是什么
MCP是模型上下文協議(Model Context Protocol)的簡稱,是一個開源協議,由Anthropic(Claude開發公司)開發,旨在讓大型語言模型(LLM)能夠以標準化的方式連接到外部數據源和工具。它就像AI應用的通用接口,幫助開發者構建更靈活、更具上下文感知能力的AI應用,而無需為每個AI模型和外部系統組合進行定制集成。MCP被設計為一個通用接口,類似于USB-C端口,允許LLM應用以一致的方式連接到各種數據源和工具,如文件、數據庫、API等。
MCP的三個概念
MCP Server
基于各語言的MCP SDK開發的程序或服務。簡單來說就是一個后端服務,這個服務提供的方法就是MCP Tool。
MCP Tool
MCP Tool 屬于MCP Server,一個MCP Server可以有多個MCP Tool。類似一個類里有多個方法,又或者一個服務里有多個接口。
MCP Client
當一段代碼,一個Agent,一個客戶端,基于MCP的規范去使用、去調用MCP Server里的MCP Tool時,它就是MCP Client。
MCP的調用流程
調用流程如圖所示,其實和function calling是類似的
MCP 案例
MCP 的兩種傳輸協議,以下案例使用 sse (http),另一種是 stdio
MCP Server
基于Spring AI 的 MCP 服務端,提供天氣預報的服務
■ 根據地區查詢當天天氣
■ 根據地區查詢近期天氣預報
// 定義 Tools
class WeatherServer {private WeatherExec weatherExec ;@Tool(name = "todayWeather", description = "根據地區查詢當日天氣")public WeatherModel todayWeather(String address) {return weatherExec.todayWeather(address);}@Tool(name = "futureWeather", description = "根據地區查詢近期天氣預報")public WeatherForecastModel futureWeather(String address) {return weatherExec.futureWeather(address);}}class Config {// 配置 Tools Bean@Beanpublic ToolCallbackProvider toolCallbackProvider(CustomService customService) {return MethodToolCallbackProvider.builder().toolObjects(customService).build();}}
MCP Client
這里僅描述 MCP 客戶端和服務端的一些交互,暫不涉及 LLM
建立連接
獲取MCP Server 的工具列表
執行一個工具
建立連接
客戶端與服務端基于 SSE 建立長連接
curl --location 'http://localhost:8080/sse'
響應 endpoint /mcp/message 即觸發事件的接口地址
發送獲取 MCP 工具列表事件
觸發事件,通過SSE返回結果
curl --location 'http://localhost:8080/mcp/message' \
--header 'Content-Type: application/json' \
--data '{"method": "tools/list","jsonrpc": "2.0","id": "xxx-id-001"
}'
sse 響應 message
{"jsonrpc": "2.0","id": "xxx-id-001","result": {"tools": [{"name": "todayWeather","description": "根據地區查詢當日天氣","inputSchema": {"type": "object","properties": {"address": {"type": "string"}}}},{...}]}
}
發送執行 MCP 工具事件
觸發事件,通過SSE返回結果
curl --location 'http://localhost:8080/mcp/message' \
--header 'Content-Type: application/json' \
--data '{"method": "tools/call","jsonrpc": "2.0","id": "xxx-id-002","params": {"name": "todayWeather","arguments": {"address": "廣州"}}
}'
sse 響應 message
{"jsonrpc": "2.0","id": "xxx-id-002","result": {"content": [{"type": "text","type": "text","text": "MCP Server 執行工具返回的數據"}],"isError": false}
}
Agent
MCP + LLM 其實就是個Agent
- 用戶向Agent提問
- Agent調用MCP Server的接口,獲取可用工具列表
- Agent調用LLM
- 非函數調用,直接回復用戶
- 函數調用則繼續
- Agent調用MCP Server的接口執行工具函數,獲取執行結果
- 再次調用大模型,獲取最終答案
- Agent回答用戶