📄 MCP 協議使用核心講解
? MCP 協議的核心在于以下幾個方面
一、MCP 請求結構(MCPRequest
)
{"messages": [{"role": "user","content": "幫我查詢一下上海的天氣"}],"tools": [{"name": "weather_query","description": "查詢天氣","parameters": {"type": "object","properties": {"location": { "type": "string", "description": "查詢地點" }},"required": ["location"]}}]
}
messages
: 聊天上下文tools
: 提供可調用的工具(函數),使用 JSON Schema 描述- 模型生成
tool_calls
請求調用工具
二、MCP 響應結構(MCPResponse
)
{"choices": [{"message": {"role": "assistant","tool_calls": [{"id": "call_123","type": "function","function": {"name": "weather_query","arguments": "{\"location\": \"上海\"}"}}]},"finish_reason": "tool_calls"}]
}
tool_calls
: 模型請求工具調用finish_reason = tool_calls
: 模型等待外部執行工具
三、工具執行結果續接請求
{"messages": [{"role": "user","content": "幫我查詢一下上海的天氣"},{"role": "assistant","tool_calls": [...]},{"role": "tool","tool_call_id": "call_123","content": "{\"weather\": \"晴天,28°C\"}"}]
}
- 工具返回結果通過
role: tool
返回,繼續對話
四、MCP 模型調用閉環流程
- 用戶發起請求(自然語言)
- 模型識別出調用意圖 → 返回
tool_calls
- 外部系統執行工具調用 → 得到結構化結果
- 將結構化結果回傳給模型(
tool
消息) - 模型基于工具結果生成最終響應
五、MCP 協議關鍵字段說明
字段名 | 說明 |
---|---|
messages | 對話上下文 |
tools | 工具定義(JSON Schema) |
tool_calls | 模型生成的調用請求 |
tool_call_id | 工具調用唯一標識 |
tool | 工具返回結果 |
finish_reason | 模型是否結束、是否等待工具調用 |
? 總結:
MCP 協議的核心在于:通過結構化的工具定義(
tools
)、模型調用請求(tool_calls
)以及工具結果反饋(tool
),實現大模型的可控、結構化、插件化調用閉環。