上篇文章,我們從零到一利用MCP協(xié)議,創(chuàng)建了一個(gè)MCP服務(wù)端,并利用 Claude 客戶(hù)端連接了服務(wù)端完成了服務(wù)中Tool的調(diào)用。今天,這篇文章,我們繼續(xù)學(xué)習(xí)MCP協(xié)議,利用MCP協(xié)議從零到一寫(xiě)一個(gè)客戶(hù)端,并將客戶(hù)端與服務(wù)端連接,調(diào)用服務(wù)端的Tool。
1. MCP環(huán)境配置
2.1 依賴(lài)
Python 3.10或更高版本 Python MCP SDK 1.2.0或更高版本
2.2 創(chuàng)建環(huán)境
(1)安裝uv
curl -LsSf https:///uv/install.sh | sh
(2)利用uv創(chuàng)建并設(shè)置項(xiàng)目
# Create project directory uv init mcp-client cd mcp-client
# Create virtual environment uv venv
# Activate virtual environment # On Windows: .venv\Scripts\activate # On Unix or MacOS: source .venv/bin/activate
asyncdefconnect_to_server(self, server_script_path: str): """Connect to an MCP server
Args: server_script_path: Path to the server script (.py or .js) """ is_python = server_script_path.endswith('.py') is_js = server_script_path.endswith('.js') ifnot (is_python or is_js): raise ValueError("Server script must be a .py or .js file")
# List available tools response = awaitself.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.name for tool in tools])
# Get next response from OpenAI response = self.openai.chat.completions.create( model="gpt-3.5-turbo", max_tokens=1000, messages=messages, tools=available_tools ) print("response:\n") print(response) final_text.append(response.choices[0].message.content) for content in response.choices[0].message.content: final_text.append(content) assistant_message_content.append(content)
return"\n".join(final_text)
2.4 連續(xù)對(duì)話(huà)封裝
asyncdefchat_loop(self): """Run an interactive chat loop""" print("\nMCP Client Started!") print("Type your queries or 'quit' to exit.")
if __name__ == "__main__": import sys asyncio.run(main())
3. 運(yùn)行
在終端命令行中運(yùn)行,運(yùn)行命令如下:
uv run client.py xxxxxx/weather/weather.py
運(yùn)行成功后,輸出如下,可以體驗(yàn)了。
4. 總結(jié)
4.1 關(guān)鍵組件
· MCPClient 類(lèi)在初始化時(shí)會(huì)進(jìn)行會(huì)話(huà)管理和 API 客戶(hù)端的配置。
· 使用 AsyncExitStack 來(lái)妥善管理資源。
· 配置 OpenAI API Key 以實(shí)現(xiàn)與 GPT模型 的交互。
4.2 總結(jié)
本文我們從零到一實(shí)現(xiàn)了一個(gè)MCP客戶(hù)端,并與我們上一篇文章中從零到一實(shí)現(xiàn)的MCP服務(wù)端進(jìn)行了連接和通信。這期間,除了上面提到的關(guān)鍵組件外,額外需要注意的是,如果你不是用的 Claude 模型,需要格外注意你所使用的大模型對(duì)function calling能力的支持,以及其需要的function calling的格式。否則很可能模型無(wú)法識(shí)別到需要用哪個(gè)tool,或者在調(diào)用tool時(shí)出錯(cuò)。