style: reformat code style

This commit is contained in:
koch3092
2025-03-12 16:42:33 +08:00
parent fcce1417f5
commit e5efc9cf7c
3 changed files with 28 additions and 40 deletions

View File

@@ -1,14 +1,11 @@
# run_mcp.py
import asyncio
import sys
from pathlib import Path
from typing import List
from dotenv import load_dotenv
from camel.models import ModelFactory
from camel.toolkits import MCPToolkit, FunctionTool
from camel.toolkits import FunctionTool
from camel.types import ModelPlatformType, ModelType
from camel.logger import set_log_level
@@ -25,11 +22,12 @@ async def construct_society(
question: str,
tools: List[FunctionTool],
) -> OwlRolePlaying:
r"""build a multi-agent OwlRolePlaying instance.
Args:
question (str): The question to ask.
tools (List[FunctionTool]): The MCP tools to use.
"""
构建一个多Agent的OwlRolePlaying实例。
这里的tools已经是用户想交给assistant使用的全部Tool集合。
"""
# 1. 创建模型
models = {
"user": ModelFactory.create(
model_platform=ModelPlatformType.OPENAI,
@@ -43,20 +41,17 @@ async def construct_society(
),
}
# 2. 配置User和Assistant
user_agent_kwargs = {"model": models["user"]}
assistant_agent_kwargs = {
"model": models["assistant"],
"tools": tools, # 直接使用外部提供的全部tools
"tools": tools,
}
# 3. 设置任务参数
task_kwargs = {
"task_prompt": question,
"with_task_specify": False,
}
# 4. 构造并返回OwlRolePlaying
society = OwlRolePlaying(
**task_kwargs,
user_role_name="user",
@@ -68,39 +63,27 @@ async def construct_society(
async def main():
# 准备MCP Servers
config_path = str(
Path(__file__).parent / "utils/mcp/mcp_servers_config.json"
)
manager = MCPToolkitManager.from_config(config_path)
# 示例问题
question = (
"I'd like a academic report about Guohao Li, including his research "
"direction, published papers (up to 20), institutions, etc."
"Then organize the report in Markdown format and save it to my desktop"
)
# 在main中统一用async with把所有MCP连接打开
# Connect to all MCP toolkits
async with manager.connection():
# 这里 manager.is_connected() = True
# 获取合并后的tools
tools = manager.get_all_tools()
# 构造Society
society = await construct_society(question, tools)
# 运行对话
answer, chat_history, token_count = await run_society(society)
# 出了 with 块这些toolkit就全部关闭
# manager.is_connected() = False
# 打印结果
print(f"\033[94mAnswer: {answer}\033[0m")
print("Chat History:", chat_history)
print("Token Count:", token_count)
if __name__ == "__main__":

View File

@@ -12,9 +12,5 @@
"args": ["-m", "mcp_simple_arxiv"]
}
},
"mcpWebServers": {
"weather": {
"url": "https://c9a9-89-185-25-132.ngrok-free.app/sse"
}
}
"mcpWebServers": {}
}

View File

@@ -7,8 +7,12 @@ from contextlib import AsyncExitStack, asynccontextmanager
class MCPToolkitManager:
"""
负责管理多个 MCPToolkit 实例,并提供统一的连接管理。
r"""MCPToolkitManager is a class for managing multiple MCPToolkit
instances and providing unified connection management.
Attributes:
toolkits (List[MCPToolkit]): A list of MCPToolkit instances to be
managed.
"""
def __init__(self, toolkits: List[MCPToolkit]):
@@ -19,17 +23,21 @@ class MCPToolkitManager:
@staticmethod
def from_config(config_path: str) -> "MCPToolkitManager":
"""从 JSON 配置文件加载 MCPToolkit 实例,并返回 MCPToolkitManager 实例。
r"""Loads an MCPToolkit instance from a JSON configuration file and
returns an MCPToolkitManager instance.
:param config_path: JSON 配置文件路径
:return: MCPToolkitManager 实例
Args:
config_path (str): The path to the JSON configuration file.
Returns:
MCPToolkitManager: The MCPToolkitManager instance.
"""
with open(config_path, "r", encoding="utf-8") as f:
data = json.load(f)
all_toolkits = []
# 处理本地 MCP 服务器
# "mcpServers" is the MCP server configuration running as stdio mode
mcp_servers = data.get("mcpServers", {})
for name, cfg in mcp_servers.items():
toolkit = MCPToolkit(
@@ -40,7 +48,7 @@ class MCPToolkitManager:
)
all_toolkits.append(toolkit)
# 处理远程 MCP Web 服务器
# "mcpWebServers" is the MCP server configuration running as sse mode
mcp_web_servers = data.get("mcpWebServers", {})
for name, cfg in mcp_web_servers.items():
toolkit = MCPToolkit(
@@ -53,10 +61,10 @@ class MCPToolkitManager:
@asynccontextmanager
async def connection(self) -> AsyncGenerator["MCPToolkitManager", None]:
"""统一打开多个 MCPToolkit 的连接,并在离开上下文时关闭。"""
r"""Connect multiple MCPToolkit instances and close them when
leaving"""
self._exit_stack = AsyncExitStack()
try:
# 顺序进入每个 toolkit 的 async context
for tk in self.toolkits:
await self._exit_stack.enter_async_context(tk.connection())
self._connected = True
@@ -67,10 +75,11 @@ class MCPToolkitManager:
self._exit_stack = None
def is_connected(self) -> bool:
r"""Returns whether the MCPToolkitManager is connected."""
return self._connected
def get_all_tools(self):
"""合并所有 MCPToolkit 提供的工具"""
r"""Returns all tools from all MCPToolkit instances."""
all_tools = []
for tk in self.toolkits:
all_tools.extend(tk.get_tools())