内容
# poly-mcp-client
[](https://opensource.org/licenses/MIT)
一个简单的 Python 客户端库,用于管理与 MCP(模型上下文协议)服务器的连接,基于官方的 [mcp-sdk](https://github.com/modelcontextprotocol/python-sdk) 构建。它适配工具定义,以便与不同的 LLM(大语言模型)供应商如 Anthropic、OpenAI 和 Gemini 一起使用。
## 特性
* **与供应商无关的工具处理:**
* 以规范格式检索可用的工具定义。
* 动态转换工具定义为与 **Anthropic**、**OpenAI** 和 **Gemini** 兼容的格式。
* **前缀命名:** 自动为工具名称和资源 URI 添加前缀 `mcp-{server_name}-`(可自定义)。这允许处理可能以相同原始名称暴露工具/资源的服务器,而不会发生冲突。
* **灵活配置:** 使用类似于 Claude Desktop 的 `claude_desktop_config.json` 的 JSON 配置文件定义 MCP 服务器。
## 状态
### 版本 0.0.1
* 核心功能(工具列表、转换、执行)已实现。
* 资源列表和读取功能已实现,但需要进一步测试。
* SSE(服务器发送事件)传输支持已实现,但需要进一步测试。
* 与提示相关的功能尚未实现。
* 这是一个早期的 alpha 版本。API 可能会发生变化。请谨慎使用。
### 版本 0.0.4
* 支持可流式传输的 HTTP 传输(仅无状态)。
## 安装
```bash
git clone https://github.com/your-username/poly-mcp-client.git
cd poly-mcp-client
pip install .
```
## 配置
创建一个 JSON 文件(例如,`mcp_servers.json`)来定义你的 MCP 服务器。结构类似于 Claude Desktop 的配置:
```json
{
"mcpServers": {
"filesystem": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/your/accessible/directory"
],
"env": null
},
"sequential-thinking": {
"type": "stdio",
"command": "npx",
"args": [
"-y", "@modelcontextprotocol/server-sequential-thinking"
]
}
}
}
```
**注意:** 确保 `command` 和 `args` 对于你的环境和服务器设置是正确的。在必要时使用绝对路径。你还需要 `npx`(通常与 Node.js 一起安装)来使用这个示例配置。
## 基本用法
本示例展示了如何从由 `PolyMCPClient` 管理的 MCP 服务器获取工具并使用它们。
### Anthropic
```python
import asyncio
import logging
import json
import os
from poly_mcp_client import PolyMCPClient # 使用正确的类名
from anthropic import Anthropic # 导入Anthropic库
from dotenv import load_dotenv
load_dotenv()
```
# 设置日志记录(可选但推荐)
logging.basicConfig(level=logging.INFO)
# 你可能想要更细致的控制,例如,仅记录 poly_mcp_client 消息
# logging.getLogger("poly_mcp_client").setLevel(logging.DEBUG)
# --- Anthropic API 密钥 ---
# 确保您的 ANTHROPIC_API_KEY 环境变量已设置
```markdown
# 例如,导出 ANTHROPIC_API_KEY='your-api-key'
anthropic_client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) # client() 从 ANTHROPIC_API_KEY 环境变量初始化
async def main():
# 初始化 PolyMCPClient
mcp_client = PolyMCPClient() # 默认前缀为 "mcp-"
await mcp_client.initialize(config_path="./mcp_servers.json") # 如有需要,请调整路径
# 等待初始连接
print("等待初始连接...")
connection_results = await mcp_client.wait_for_initial_connections(timeout=45.0)
print("初始连接结果:", connection_results)
# 检查是否有服务器成功连接
successful_connections = [name for name, (success, _) in connection_results.items() if success]
if not successful_connections:
print("没有成功连接的 MCP 服务器。正在退出。")
await mcp_client.shutdown()
return
print(f"成功连接到: {successful_connections}")
try:
# 1. 获取 Anthropic 格式的可用工具
print("\n正在获取 Anthropic 的工具...")
anthropic_tools = await mcp_client.get_available_tools(vendor="anthropic")
print(f"找到 {len(anthropic_tools)} 个工具(Anthropic 格式)。")
# 2. 定义用户的消息
# 示例:请求 Claude 列出桌面上的文件,使用文件系统服务器
user_message = "你能列出我文件夹中的所有文件吗?"
messages = [{"role": "user", "content": user_message}]
print(f"\n正在向 Claude 发送请求,使用 {len(anthropic_tools)} 个工具...")
# 3. 调用 Anthropic API(初始请求)
response = anthropic_client.messages.create(
model="claude-3-7-sonnet-20250219", # 或者你喜欢的模型
max_tokens=1024,
messages=messages,
tools=anthropic_tools,
)
print("\nClaude 的初始响应类型:", response.stop_reason)
# 4. 处理响应 - 检查工具使用情况
while response.stop_reason == "tool_use":
tool_results = []
for content_block in response.content:
if content_block.type == "tool_use":
tool_name = content_block.name
tool_input = content_block.input
tool_use_id = content_block.id
print(f"\nClaude 想要使用工具: {tool_name}")
print(f"输入内容: {tool_input}")
# 5. 使用 PolyMCPClient 执行工具
try:
tool_output_content = await mcp_client.execute_mcp_tool(
full_tool_name=tool_name,
arguments=tool_input
)
print(f"工具 '{tool_name}' 执行成功。")
# 6. 为 Anthropic 格式化结果
# 从 'execute_mcp_tool' 接收到的 'tool_output_content' 是一个列表
# 包含内容项(如 TextContent、ImageContent)。方便的是,
# MCP SDK 对该列表的结构设计为与 Anthropic 的 'tool_result'
# 内容块所期望的列表格式直接兼容。
# 因此,对于 Anthropic,我们可以直接传递 'tool_output_content'。
# 如果使用不同的供应商(如 OpenAI 或 Gemini),则需要
# 在此处将 'tool_output_content' 转换为该供应商特定的
# 所需格式(例如,OpenAI 函数调用的单个 JSON 字符串)。
tool_results.append({
"type": "tool_result",
"tool_use_id": tool_use_id,
```
```python
"content": tool_output_content, # 直接传递列表给 Anthropic
# 注意:如果 execute_mcp_tool 引发了下面处理的错误,
# 这个 'content' 将被错误消息内容覆盖。
})
except (ValueError, ConnectionError, RuntimeError, TimeoutError, Exception) as e:
print(f"执行工具 '{tool_name}' 时出错: {e}")
# 将错误报告回 Claude
tool_results.append({
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": f"执行工具时出错: {str(e)}",
})
# 如果有工具结果,将它们添加到消息历史中
if tool_results:
messages.append({"role": "assistant", "content": response.content}) # 添加 Claude 的回合
messages.append({"role": "user", "content": tool_results}) # 添加工具结果
# 7. 再次调用 Anthropic API,传入工具结果
print("\n将工具结果发送回 Claude...")
response = anthropic_client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
messages=messages,
tools=anthropic_tools,
)
print("\n工具执行后 Claude 的响应类型:", response.stop_reason)
else:
# 如果 stop_reason 是 tool_use,但没有生成工具结果,这种情况不应该发生,但防御性地中断
print("警告: stop_reason 是 'tool_use' 但没有生成工具结果。")
break
# 8. 处理 Claude 的最终响应
print("\nClaude 的最终响应:")
final_text = ""
for content_block in response.content:
if content_block.type == "text":
print(content_block.text)
final_text += content_block.text + "\n"
if not final_text:
print("(最终响应中没有文本内容)")
print("完整的最终响应对象:", response)
except Exception as e:
print(f"\n发生意外错误: {e}")
logging.exception("主执行期间出错:") # 记录堆栈跟踪
finally:
# 优雅地关闭客户端
print("\n正在关闭 PolyMCPClient...")
await mcp_client.shutdown()
print("关闭完成。")
if __name__ == "__main__":
# 运行异步主函数的示例
# 确保在支持顶级 await 的环境中运行此代码
# 或使用 asyncio.run()
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n用户中断。")
```
### Gemini (Google AI Studio)
```python
import asyncio
import logging
import os
from poly_mcp_client import PolyMCPClient
from dotenv import load_dotenv
from google import genai
from google.genai.types import (
ToolConfig,
FunctionCallingConfig,
GenerateContentConfig,
Content,
Part,
Tool,
FunctionDeclaration,
)
```
# 加载环境变量(用于 API 密钥)
load_dotenv()
# 设置日志记录(可选)
logging.basicConfig(level=logging.INFO)
# --- Google API 密钥 ---
# 确保您的 GEMINI_API_KEY 环境变量已设置
# 例如,导出 GEMINI_API_KEY='your-api-key'
genai_client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
async def main():
# 初始化 PolyMCPClient
mcp_client = PolyMCPClient() # 默认前缀为 "mcp-"
await mcp_client.initialize(config_path="./mcp_servers.json")
# 等待初始连接(重要!)
print("等待初始连接...")
connection_results = await mcp_client.wait_for_initial_connections(timeout=45.0)
print("初始连接结果:", connection_results)
# 检查是否有服务器成功连接
successful_connections = [name for name, (success, _) in connection_results.items() if success]
if not successful_connections:
print("没有成功连接的 MCP 服务器。正在退出。")
await mcp_client.shutdown()
return
print(f"成功连接到: {successful_connections}")
try:
# 1. 获取以 Gemini 格式提供的工具
print("\n正在获取 Google Gemini 的工具...")
# get_available_tools 方法返回适合 FunctionDeclaration 的字典
gemini_tool_dicts = await mcp_client.get_available_tools(vendor="google")
print(f"找到 {len(gemini_tool_dicts)} 个工具(Gemini 格式)。")
# 为 API 调用准备工具
if gemini_tool_dicts:
gemini_tools = [Tool(function_declarations=[FunctionDeclaration(**tool) for tool in gemini_tool_dicts])]
tool_config = ToolConfig(
function_calling_config=FunctionCallingConfig(mode='AUTO') # 模式 'ANY': 允许模型在任何回合预测函数调用。
)
else:
gemini_tools = []
tool_config = None # 没有工具,不需要工具配置
# 2. 定义用户消息
# 根据您配置的服务器和路径调整用户消息
user_message = "你能列出我文件夹中的所有文件吗? path/to/folder"
# 3. 初始化聊天历史
history = []
latest_content = Content(parts=[Part.from_text(text=user_message)], role="user")
history.append(latest_content) # 将初始用户消息添加到历史记录中
print(f"\n正在向 Gemini 发送请求,使用 {len(gemini_tool_dicts)} 个工具...")
while True: # 持续交互,直到模型以文本响应
# 4. 为 API 调用准备生成配置
generation_config = GenerateContentConfig(
temperature=0.7, # 根据需要调整生成参数
max_output_tokens=1024,
tools=gemini_tools if gemini_tools else None, # 如果可用则传递工具
tool_config=tool_config if tool_config else None, # 如果可用则传递工具配置
)
# 5. 调用 Google Gemini API
response = await genai_client.aio.models.generate_content(
model="gemini-2.0-flash", # 使用适当的模型名称
contents=history, # 传递完整的聊天历史
config=generation_config
)
# 6. 处理响应 - 检查函数调用或文本
candidate = response.candidates[0] # 获取第一个候选项
first_part = candidate.content.parts[0] if candidate.content.parts else None
if first_part and hasattr(first_part, 'function_call') and first_part.function_call:
function_call = first_part.function_call
print(f"\nGemini 想要使用工具: {function_call.name}")
print(f"输入: {function_call.args}")
# 将模型请求使用该函数的内容添加到历史记录中
model_turn_parts = [Part.from_function_call(name=function_call.name, args=function_call.args)]
history.append(Content(role="model", parts=model_turn_parts))
```markdown
# 7. 使用 PolyMCPClient 执行工具
try:
# execute_mcp_tool 期望参数为字典格式
tool_args_dict = dict(function_call.args.items()) if function_call.args else {}
tool_output_content = await mcp_client.execute_mcp_tool(
full_tool_name=function_call.name,
arguments=tool_args_dict
)
print(f"工具 '{function_call.name}' 执行成功。")
# 8. 格式化结果以供 Gemini 使用
# 将 MCP 内容项的列表(TextContent 等)转换为 Gemini Part 对象的列表,使用 Part.from_function_response。
function_response_parts = []
for mcp_item in tool_output_content:
# Gemini 的函数响应 'response' 字段期望一个字典。
# 我们在这里包装 MCP 项的详细信息(转换为字典)。
# 如果工具返回非文本内容(例如,图像),请调整此逻辑。
if hasattr(mcp_item, 'text'):
# 传递 MCP 项的字典表示
response_data = {"content": mcp_item.model_dump()}
function_response_parts.append(
Part.from_function_response(
name=function_call.name,
response=response_data
)
)
# else: 如有需要,处理其他 MCP 内容类型(ImageContent 等)
if not function_response_parts:
# 处理工具执行但没有适合 Gemini 输出的情况
print(f"警告:工具 '{function_call.name}' 执行成功,但未生成可转换的输出。")
function_response_parts.append(
Part.from_function_response(
name=function_call.name,
response={"content": "工具执行成功,但未提供标准输出。"}
)
)
# 将函数执行结果添加到历史记录中(根据 Gemini 文档作为 'user' 角色)
history.append(Content(role="user", parts=function_response_parts))
print("\n正在将工具结果发送回 Gemini...")
# 循环继续调用 generate_content
tool_config = ToolConfig(
function_calling_config=FunctionCallingConfig(mode='AUTO') # 模式 'AUTO': 模型自动决定是否使用函数调用。
)
except (ValueError, ConnectionError, RuntimeError, TimeoutError, Exception) as e:
print(f"执行工具 '{function_call.name}' 时出错:{e}")
# 将错误报告回 Gemini
error_response_part = Part.from_function_response(
name=function_call.name,
# 在响应内容中提供错误信息
response={"error": f"执行工具失败:{str(e)}"}
)
# 将错误结果添加到历史记录
history.append(Content(role="user", parts=[error_response_part]))
print("\n正在将错误信息发送回 Gemini...")
# 循环继续调用 generate_content
elif first_part and hasattr(first_part, 'text'):
# 9. 处理来自 Gemini 的最终文本响应
```
```python
print("\nGemini的最终响应:")
final_text = ""
# 遍历最终响应中的所有部分,以防有多个文本部分
for part in candidate.content.parts:
if hasattr(part, 'text'):
print(part.text)
final_text += part.text + "\n"
if not final_text:
print("(最终响应中没有文本内容)")
# print("完整的最终响应对象:", response) # 用于调试
# 将最终模型响应添加到历史记录中(可选,如果继续聊天)
history.append(candidate.content)
break # 退出循环,因为我们有最终的文本响应
else:
# 处理意外的响应内容
print("\n从Gemini接收到意外的响应内容:")
print(response)
break # 在意外响应时退出循环
except Exception as e:
print(f"\n发生了意外错误:{e}")
logging.exception("主执行期间发生错误:") # 记录堆栈跟踪
finally:
# 优雅地关闭客户端
print("\n正在关闭PolyMCPClient...")
await mcp_client.shutdown()
print("关闭完成。")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n用户中断。")
```
## 依赖项
* [mcp-sdk](https://github.com/modelcontextprotocol/python-sdk)
* [pydantic](https://docs.pydantic.dev/)
## 许可证
本项目采用 MIT 许可证 - 详细信息请参见 [LICENSE](LICENSE) 文件。
连接信息
猜你喜欢
暂无推荐服务器