MCP 3.0協議詳解:構建AI與工具的橋樑
深入理解MCP 3.0協議的核心概念,學習如何開發MCP Server和Client,構建AI與外部工具的橋樑。
MCP簡介
Model Context Protocol(MCP)是由Anthropic提出的開放協議,旨在標準化AI模型與外部工具和資料來源之間的通訊方式。MCP 3.0是該協議的最新版本,帶來了更強大的功能和更安全的架構設計。
MCP解決了一個核心問題:如何讓AI模型安全、高效地存取外部工具和資料。在MCP出現之前,每個AI應用都需要自己實現工具整合,導致了大量重複工作和安全隱患。MCP透過定義標準化的通訊協議,讓工具開發者和AI應用開發者可以各司其職,大幅降低了整合成本。
MCP 3.0新特性
- 支援串流式回應,提升使用者體驗
- 增強的權限模型,更細粒度的存取控制
- 支援工具組合和鏈式呼叫
- 改進的錯誤處理和恢復機制
- 原生支援多模態資料傳輸
核心概念
理解MCP的核心概念是開發MCP應用的基礎。MCP採用Client-Server架構,透過標準化的訊息格式進行通訊。
MCP Host
發起連接的AI應用程式,如Claude Desktop或IDE。Host負責管理多個Client連接,協調工具呼叫。
MCP Client
在Host內部運行,與Server保持一對一連接。Client負責協議握手、訊息路由和連接生命週期管理。
MCP Server
提供工具和資料的服務端。每個Server獨立提供特定功能,如檔案系統存取、資料庫查詢等。
通訊協議
// MCP 3.0 訊息格式
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "read_file",
"arguments": {
"path": "/path/to/file",
"encoding": "utf-8"
}
}
}
// 回應格式
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "檔案內容..."
}
]
}
}
Server開發
開發MCP Server是構建工具整合的核心。以下展示如何使用Python和TypeScript開發MCP Server。
Python MCP Server
from mcp.server import Server
from mcp.types import Tool, TextContent
import mcp.server.stdio
server = Server("file-reader")
@server.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name="read_file",
description="讀取指定路徑的檔案內容",
inputSchema={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "檔案路徑"
},
"encoding": {
"type": "string",
"default": "utf-8",
"description": "檔案編碼"
}
},
"required": ["path"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "read_file":
path = arguments["path"]
encoding = arguments.get("encoding", "utf-8")
try:
with open(path, "r", encoding=encoding) as f:
content = f.read()
return [TextContent(type="text", text=content)]
except FileNotFoundError:
return [TextContent(type="text", text=f"錯誤:找不到檔案 {path}")]
except Exception as e:
return [TextContent(type="text", text=f"錯誤:{str(e)}")]
async def main():
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
Client開發
MCP Client負責與Server建立連接並呼叫工具。以下展示如何開發一個基本的MCP Client。
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from contextlib import AsyncExitStack
class MCPClient:
def __init__(self):
self.session: ClientSession | None = None
self.exit_stack = AsyncExitStack()
async def connect(self, server_script: str):
"""連接到MCP Server"""
server_params = StdioServerParameters(
command="python",
args=[server_script],
env=None
)
stdio_transport = await self.exit_stack.enter_async_context(
stdio_client(server_params)
)
read_stream, write_stream = stdio_transport
self.session = await self.exit_stack.enter_async_context(
ClientSession(read_stream, write_stream)
)
await self.session.initialize()
response = await self.session.list_tools()
print(f"已連接,可用工具: {[t.name for t in response.tools]}")
async def call_tool(self, tool_name: str, arguments: dict):
"""呼叫MCP工具"""
if not self.session:
raise RuntimeError("未連接到Server")
result = await self.session.call_tool(tool_name, arguments)
return result
async def cleanup(self):
"""清理資源"""
await self.exit_stack.aclose()
async def main():
client = MCPClient()
try:
await client.connect("server.py")
result = await client.call_tool("read_file", {"path": "test.txt"})
print(result)
finally:
await client.cleanup()
if __name__ == "__main__":
import asyncio
asyncio.run(main())
安全實踐
MCP 3.0引入了增強的安全模型,開發者必須遵循安全最佳實踐來保護使用者的資料和系統。
權限控制
MCP 3.0支援細粒度的權限控制。Server應該明確聲明每個工具所需的權限,Client應該在使用者確認後才授予權限。永遠不要預設授予所有權限,遵循最小權限原則。
輸入驗證
所有來自Client的輸入都必須進行嚴格驗證。使用JSON Schema驗證工具參數,防止注入攻擊和路徑穿越等安全問題。不要信任任何外部輸入。
資料隔離
每個MCP Server應該運行在獨立的沙箱環境中,限制其對系統資源的存取。使用容器化技術確保Server之間的隔離,防止橫向移動攻擊。
部署指南
將MCP Server部署到生產環境需要考慮效能、可靠性和安全性等多個方面。以下是推薦的部署架構和最佳實踐。
# Docker部署範例
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# 使用非root使用者運行
RUN useradd -m mcp_user
USER mcp_user
# 健康檢查
HEALTHCHECK --interval=30s --timeout=10s \
CMD python -c "import requests; requests.get('http://localhost:8000/health')"
CMD ["python", "server.py"]
部署最佳實踐
- 使用容器化部署,確保環境一致性
- 實現健康檢查和自動重啟機制
- 配置適當的資源限制(CPU、記憶體)
- 使用TLS加密通訊通道
- 實現日誌記錄和監控
- 定期更新依賴項修復安全漏洞
總結
MCP 3.0為AI與外部工具的整合提供了標準化的解決方案。透過MCP,開發者可以輕鬆地將各種工具和資料來源整合到AI應用中,而無需為每個工具編寫特定的整合程式碼。
隨著MCP生態系統的不斷發展,我們期待看到更多創新的工具和應用出現。無論你是工具開發者還是AI應用開發者,MCP都為你提供了一個強大而靈活的平台。歡迎加入MCP社群,共同推動AI工具整合的標準化進程。