安裝fastmcp
pip install fastmcp
編寫mcp服務端代碼
from fastmcp import FastMCP
mcp= FastMCP('weather')@mcp.tool()
def get_weather(city: str):'''獲取對應城市的天氣:param city: 目標城市:return: 該城市的天氣'''return f"{city}天氣晴朗,溫度60度!"
@mcp.tool()
def get_price(meat: str):'''獲取肉類價格:param meat: 肉類名稱:return: 肉類對應的價格'''return f"{meat}價格35元每斤!"if __name__ == '__main__':mcp.run(transport='stdio')
編寫mcp客戶端代碼
from fastmcp import Client
import asyncioasync def run():# 客戶端實例化!傳入服務端的代碼腳本client = Client('server.py')# 異步調用調用clientasync with client:# 獲取服務端工具列表!tools = await client.list_tools()# 調用服務端工具response = await client.call_tool('{}'.format(tools[1].name),{'meat':'豬肉'})print(response)if __name__ == '__main__':asyncio.run(run())