🚀 使用模型上下文協議(MCP)構建服務器和客戶端的分步指南
本指南將詳細介紹如何使用模型上下文協議(MCP)構建服務器和客戶端,幫助你快速搭建分佈式計算系統。
✨ 主要特性
- 提供服務器和客戶端的完整項目結構。
- 支持命令行和圖形用戶界面(GUI)兩種客戶端交互方式。
- 易於擴展,可添加更多工具和功能。
📦 安裝指南
服務器端
pip install mcp-server
客戶端
pip install mcp-client
客戶端 GUI
pip install tkinter mcp-client
💻 使用示例
服務器端示例
基礎用法
from mcp_server import Server, Tool
class CalculatorTool(Tool):
def add(self, a: int, b: int) -> int:
return a + b
if __name__ == "__main__":
server = Server()
server.add_tool(CalculatorTool())
server.start()
客戶端示例
基礎用法(命令行)
from mcp_client import ServerConnector
connector = ServerConnector("localhost", 1234)
tools = await connector.connect()
calculator_tool = tools["Calculator"]
result = await calculator_tool.add(5, 3)
高級用法(GUI)
import tkinter as tk
from mcp_client import ServerConnector
class CalculatorApp:
def __init__(self):
self.window = tk.Tk()
self.window.title("MCP 計算器客戶端")
self.entry1 = tk.Entry(self.window)
self.entry2 = tk.Entry(self.window)
self.button = tk.Button(self.window, text="計算", command=self.calculate)
self.result_label = tk.Label(self.window, text="")
self.entry1.pack()
self.entry2.pack()
self.button.pack()
self.result_label.pack()
def calculate(self):
try:
a = int(self.entry1.get())
b = int(self.entry2.get())
connector = ServerConnector("localhost", 1234)
tools = connector.connect_synchronously()
calculator_tool = tools["Calculator"]
result = calculator_tool.add(a, b)
self.result_label.config(text=f"結果: {result}")
except Exception as e:
self.result_label.config(text=f"錯誤: {str(e)}")
if __name__ == "__main__":
app = CalculatorApp()
app.window.mainloop()
📚 詳細文檔
創建 MCP 服務器的步驟
步驟一: 安裝所需庫
pip install mcp-server
步驟二: 初始化項目結構
mkdir server
cd server
nano server.py
在文件中添加以下內容:
from mcp_server import Server, Tool
class CalculatorTool(Tool):
def add(self, a: int, b: int) -> int:
return a + b
if __name__ == "__main__":
server = Server()
server.add_tool(CalculatorTool())
server.start()
保存並關閉文件。
步驟三: 啟動服務器
cd ..
python -m server.server_project_name.server
創建 MCP 客戶端的步驟
步驟一: 安裝所需庫
pip install mcp-client
步驟二: 初始化項目結構
mkdir client
cd client
nano server_connector.py
在文件中添加以下內容:
from mcp_client import ServerConnector
async def main():
connector = ServerConnector("localhost", 1234)
tools = await connector.connect()
calculator_tool = tools["Calculator"]
result = await calculator_tool.add(5, 3)
print(f"Result: {result}")
if __name__ == "__main__":
import asyncio
asyncio.run(main())
保存並關閉文件。
步驟三: 運行客戶端
cd ..
python -m client.server_connector
創建 MCP 客戶端圖形用戶界面(GUI)
步驟一: 安裝 GUI 庫
pip install tkinter mcp-client
步驟二: 初始化項目結構
mkdir client_ui
cd client_ui
nano app.py
在文件中添加以下內容:
import tkinter as tk
from mcp_client import ServerConnector
class CalculatorApp:
def __init__(self):
self.window = tk.Tk()
self.window.title("MCP 計算器客戶端")
self.entry1 = tk.Entry(self.window)
self.entry2 = tk.Entry(self.window)
self.button = tk.Button(self.window, text="計算", command=self.calculate)
self.result_label = tk.Label(self.window, text="")
self.entry1.pack()
self.entry2.pack()
self.button.pack()
self.result_label.pack()
def calculate(self):
try:
a = int(self.entry1.get())
b = int(self.entry2.get())
connector = ServerConnector("localhost", 1234)
tools = connector.connect_synchronously()
calculator_tool = tools["Calculator"]
result = calculator_tool.add(a, b)
self.result_label.config(text=f"結果: {result}")
except Exception as e:
self.result_label.config(text=f"錯誤: {str(e)}")
if __name__ == "__main__":
app = CalculatorApp()
app.window.mainloop()
保存並關閉文件。
步驟三: 運行 GUI 應用程序
cd ..
python -m client_ui.app
🔧 技術細節
項目結構
服務器端 (server
目錄)
- 位置:
server/server_project_name/server.py
- 內容: 包含服務器核心邏輯、工具定義以及組件配置。
客戶端 (client
目錄)
- 位置:
client/mcp_client/server_connector.py
- 內容: 包含連接到服務器的邏輯以及與服務器交互的功能。
擴展系統
- 添加更多工具: 在服務器中定義新的工具類,並在
server.py
中註冊它們。
- 增強 GUI: 向客戶端 GUI 添加更多功能,例如減法、乘法和除法操作。
- 配置管理: 創建配置文件以管理服務器地址和其他設置。
- 日誌記錄: 實施日誌記錄以跟蹤客戶端和服務器之間的交互。
測試系統
服務器端測試
cd server
python server.py
客戶端命令行測試
cd ..
cd client
python server_connector.py
客戶端 GUI 測試
cd ..
cd client_ui
python app.py
結論
模型上下文協議(MCP)提供了一種強大的方法來構建分佈式計算系統。通過遵循本指南,您將能夠創建功能完善的服務器和客戶端,並擴展它們以滿足各種需求。繼續探索 MCP 的潛力,並將其應用於您的項目中!