MCP是什么?
MCP 服務 = 代理服務(Proxy) + 標準化接口 + 自動化適配
MCP 的目的,就是讓 AI 應用不再“為每個工具定制對接 ”,而是像使用 USB-C 一樣,“插上即用”任何外部工具。
沒mcp之前不同的工具入參和出參千奇百怪,需要程序員針對不同工具接口,輸入不同形式的入參,出參也要進行特殊的解析處理。有了mcp服務,AI應用就能遵循統一標準入參,統一標準回參。
更加通俗說明:MCP服務作用,它好比一個可插拔多功能的螺絲刀,想用那個刀頭如十字的,一字的,六角的,梅花的,而各種不同的刀頭就代表著不同的工具或服務。當需要使用某個特定的工具時,只需要將對應的“刀頭”插入MCP這個“螺絲刀柄”中,就可以開始工作了,這種設計使得切換不同的工具變得非常簡單和快捷,不需要為每種工具準備一個單獨的螺絲刀,而且,這個多功能螺絲刀還很智能,它知道每個刀頭的用途和使用方法(就像MCP了解每個服務的接口和參數一樣),所以你不需要成為工具專家,也能輕松完成任務。
對應到 AI 應用調用工具:
MCP 服務會通過標準接口(/tools
)告訴 AI:
“我支持這些工具:
? ? ? ? read_file(path: string):讀文件,需要傳一個路徑
send_email(to: string, subject: string, body: string):發郵件,需要收件人、主題、內容
這個描述是用 JSON Schema 寫的,AI 能“看懂”。
{"tool": "send_email","input": {"to": "zhangsan@company.com","subject": "會議紀要","body": "這是重點內容..."}
}
AI 應用 MCP 服務(本地/遠程)│ ││ 第一次調用:發現能力 ││──────────────────────────────────?││ GET /mcp/v1/tools ││ ││ 返回:我支持哪些工具 ││?──────────────────────────────────││ [ ││ { ││ "name": "read_file", ││ "inputSchema": { ... } ││ }, ││ { ││ "name": "send_email", ││ "inputSchema": { ... } ││ } ││ ] ││ ││ 第二次調用:執行操作 ││──────────────────────────────────?││ POST /mcp/v1/invoke ││ { ││ "tool": "send_email", ││ "input": { ││ "to": "zhangsan@...", ││ "subject": "..." ││ } ││ } ││ ││ 返回執行結果 ││?──────────────────────────────────││ { "result": "success" } │
SpringAI:
@Tool:“這個方法是一個可被 AI應用 調用的工具’”
@ToolInput:?可以描述參數用途
// 2. 在 @Tool 方法中使用對象
@Component
public class WeatherTools {@Tool(description = "根據城市查詢天氣")public String getWeatherHistory(WeatherRequest request) {return weatherService.fetchHistory(request.getCity(), request.getDate(), request.isIncludeTempDetail());}
}
// 1. 定義請求對象
public class WeatherRequest {@ToolInput(description = "城市名稱,例如:北京、上海")private String city;@ToolInput(description = "查詢日期,格式:yyyy-MM-dd")private String date;@ToolInput(description = "是否包含氣溫詳情,true 或 false")private boolean includeTempDetail;// 必須提供 getter 方法,Spring AI 需要通過它讀取字段public String getCity() { return city; }public String getDate() { return date; }public boolean isIncludeTempDetail() { return includeTempDetail; }// 可選:提供 setter 或構造函數public void setCity(String city) { this.city = city; }public void setDate(String date) { this.date = date; }public void setIncludeTempDetail(boolean includeTempDetail) { this.includeTempDetail = includeTempDetail; }
}
Spring AI工作流程:
第一步:Spring啟動時,掃描所有被 @Component
、@Service
等注解標記的 Bean,查找帶有 @Tool
的方法
第二步:提取元數據,生成?MCP 工具描述(Tool Schema)
{"name": "getWeather","description": "根據城市查詢天氣","inputSchema": {"type": "object","properties": {"city": {"type": "string","description": "城市名稱"}},"required": ["city"]}
}
第三步:暴露標準 MCP 接口
pring AI 會自動為你啟動一個 MCP Server,并提供兩個標準 HTTP 接口:
1.?GET /mcp/v1/tools?
—— 返回所有?@Tool
?方法的描述
[{"name": "getWeather","description": "根據城市查詢天氣","inputSchema": { ... }}
]
2.?POST /mcp/v1/invoke
?—— 接收 AI 的調用請求
當 AI 應用想調用 getWeather
時,會發:
{"tool": "getWeather","input": {"city": "北京"}
}
第四步:MCP Server 調用對應的方法 getWeather
把返回結果包裝成標準格式返回給 AI
{ "result": "北京:晴,28°C" }