Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

Debug: Enhance the support of running mcp in sync mode (#2575)

Xiaotian Jin94457351d3c6
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index c2ff40168..f25dc622a 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -1560,8 +1560,32 @@ class ChatAgent(BaseAgent):
args = tool_call_request.args
tool_call_id = tool_call_request.tool_call_id
tool = self._internal_tools[func_name]
+ import asyncio
+
try:
- result = await tool.async_call(**args)
+ # Try different invocation paths in order of preference
+ if hasattr(tool, 'func') and hasattr(tool.func, 'async_call'):
+ # Case: FunctionTool wrapping an MCP tool
+ result = await tool.func.async_call(**args)
+
+ elif hasattr(tool, 'async_call') and callable(tool.async_call):
+ # Case: tool itself has async_call
+ result = await tool.async_call(**args)
+
+ elif hasattr(tool, 'func') and asyncio.iscoroutinefunction(
+ tool.func
+ ):
+ # Case: tool wraps a direct async function
+ result = await tool.func(**args)
+
+ elif asyncio.iscoroutinefunction(tool):
+ # Case: tool is itself a coroutine function
+ result = await tool(**args)
+
+ else:
+ # Fallback: synchronous call
+ result = tool(**args)
+
except Exception as e:
# Capture the error message to prevent framework crash
error_msg = f"Error executing async tool '{func_name}': {e!s}"
diff --git a/camel/agents/mcp_agent.py b/camel/agents/mcp_agent.py
index c1d13c45c..ea780a013 100644
--- a/camel/agents/mcp_agent.py
+++ b/camel/agents/mcp_agent.py
@@ -125,6 +125,7 @@ class MCPAgent(ChatAgent):
local_config_path: Optional[str] = None,
tools: Optional[List[Union[FunctionTool, Callable]]] = None,
function_calling_available: bool = True,
+ strict: bool = False,
**kwargs,
):
if model is None:
@@ -144,6 +145,7 @@ class MCPAgent(ChatAgent):
self.local_config = local_config
self.function_calling_available = function_calling_available
+ self.strict = strict
if function_calling_available:
sys_msg_content = "You are a helpful assistant, and you prefer "
@@ -177,7 +179,7 @@ class MCPAgent(ChatAgent):
if self.local_config:
config_dict.update(self.local_config)
- return MCPToolkit(config_dict=config_dict)
+ return MCPToolkit(config_dict=config_dict, strict=self.strict)
def add_registry(self, registry_config: BaseMCPRegistryConfig) -> None:
r"""Add a new registry configuration to the agent.
@@ -211,6 +213,7 @@ class MCPAgent(ChatAgent):
] = None,
model: Optional[BaseModelBackend] = None,
function_calling_available: bool = False,
+ strict: bool = False,
**kwargs,
) -> "MCPAgent":
r"""Create and connect an MCPAgent instance.
@@ -276,6 +279,7 @@ class MCPAgent(ChatAgent):
registry_configs=final_registry_configs,
model=model,
function_calling_available=function_calling_available,
+ strict=strict,
**kwargs,
)
diff --git a/camel/toolkits/mcp_toolkit.py b/camel/toolkits/mcp_toolkit.py
index d2228264a..8c6f1de3b 100644
--- a/camel/toolkits/mcp_toolkit.py
+++ b/camel/toolkits/mcp_toolkit.py
@@ -98,6 +98,8 @@ class MCPToolkit(BaseToolkit):
timeout (Optional[float], optional): Timeout for connection attempts
in seconds. This timeout applies to individual client connections.
(default: :obj:`None`)
+ strict (Optional[bool], optional): Flag to indicate strict mode.
+ (default: :obj:`False`)
Note:
At least one of :obj:`clients`, :obj:`config_path`, or
@@ -146,6 +148,7 @@ class MCPToolkit(BaseToolkit):
config_path: Optional[str] = None,
config_dict: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
+ strict: Optional[bool] = False,
):
# Call parent constructor first
super().__init__(timeout=timeout)
@@ -162,6 +165,7 @@ class MCPToolkit(BaseToolkit):
raise ValueError(error_msg)
self.clients: List[MCPClient] = clients or []
+ self.strict = strict # Store strict parameter
self._is_connected = False
self._exit_stack: Optional[AsyncExitStack] = None
@@ -309,6 +313,7 @@ class MCPToolkit(BaseToolkit):
config_path: Optional[str] = None,
config_dict: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
+ strict: Optional[bool] = False,
) -> "MCPToolkit":
r"""Factory method that creates and connects to all MCP servers.
@@ -326,6 +331,8 @@ class MCPToolkit(BaseToolkit):
config file. (default: :obj:`None`)
timeout (Optional[float], optional): Timeout for connection
attempts in seconds. (default: :obj:`None`)
+ strict (Optional[bool], optional): Flag to indicate strict mode.
+ (default: :obj:`False`)
Returns:
MCPToolkit: A fully initialized and connected :obj:`MCPToolkit`
@@ -354,6 +361,7 @@ class MCPToolkit(BaseToolkit):
config_path=config_path,
config_dict=config_dict,
timeout=timeout,
+ strict=strict,
)
try:
await toolkit.connect()
@@ -373,10 +381,11 @@ class MCPToolkit(BaseToolkit):
config_path: Optional[str] = None,
config_dict: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
+ strict: Optional[bool] = False,
) -> "MCPToolkit":
r"""Synchronously create and connect to all MCP servers."""
return run_async(cls.create)(
- clients, config_path, config_dict, timeout
+ clients, config_path, config_dict, timeout, strict
)
def _load_clients_from_config(self, config_path: str) -> List[MCPClient]:
@@ -433,10 +442,12 @@ class MCPToolkit(BaseToolkit):
try:
# Use the new mcp_client factory function
- # Pass timeout from toolkit if available
+ # Pass timeout and strict from toolkit if available
kwargs = {}
if hasattr(self, "timeout") and self.timeout is not None:
kwargs["timeout"] = self.timeout
+ if hasattr(self, "strict") and self.strict is not None:
+ kwargs["strict"] = self.strict
client = create_mcp_client(cfg, **kwargs)
return client
diff --git a/camel/utils/mcp_client.py b/camel/utils/mcp_client.py
index 8c8822873..ebd7914fb 100644
--- a/camel/utils/mcp_client.py
+++ b/camel/utils/mcp_client.py
@@ -559,8 +559,8 @@ class MCPClient:
MCP server.
Returns:
- Callable: A dynamically created async Python function that wraps
- the MCP tool.
+ Callable: A dynamically created Python function that wraps
+ the MCP tool and works in both sync and async contexts.
"""
func_name = mcp_tool.name
func_desc = mcp_tool.description or "No description provided."
@@ -589,16 +589,9 @@ class MCPClient:
func_params.append(param_name)
- async def dynamic_function(**kwargs) -> str:
- r"""Auto-generated function for MCP Tool interaction.
-
- Args:
- kwargs: Keyword arguments corresponding to MCP tool parameters.
-
- Returns:
- str: The textual result returned by the MCP tool.
- """
-
+ # Create the async version of the function
+ async def async_mcp_call(**kwargs) -> str:
+ r"""Async version of MCP tool call."""
missing_params: Set[str] = set(required_params) - set(
kwargs.keys()
)
@@ -661,9 +654,83 @@ class MCPClient:
)
raise e
- dynamic_function.__name__ = func_name
- dynamic_function.__doc__ = func_desc
- dynamic_function.__annotations__ = annotations
+ def adaptive_dynamic_function(**kwargs) -> str:
+ r"""Adaptive function that works in both sync and async contexts.
+
+ This function detects if it's being called from an async context
+ and behaves accordingly.
+
+ Args:
+ kwargs: Keyword arguments corresponding to MCP tool parameters.
+
+ Returns:
+ str: The textual result returned by the MCP tool.
+
+ Raises:
+ TimeoutError: If the operation times out.
+ RuntimeError: If there are issues with async execution.
+ """
+ import asyncio
+ import concurrent.futures
+
+ try:
+ # Check if we're in an async context with a running loop
+ loop = asyncio.get_running_loop() # noqa: F841
+ # If we get here, we're in an async context with a running loop
+ # We need to run the async function in a separate thread with
+ # a new loop
+
+ def run_in_thread():
+ # Create a new event loop for this thread
+ new_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(new_loop)
+ try:
+ return new_loop.run_until_complete(
+ async_mcp_call(**kwargs)
+ )
+ except Exception as e:
+ # Preserve the original exception context
+ raise RuntimeError(
+ f"MCP call failed in thread: {e}"
+ ) from e
+ finally:
+ new_loop.close()
+
+ # Run in a separate thread to avoid event loop conflicts
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(run_in_thread)
+ try:
+ return future.result(
+ timeout=self.read_timeout_seconds.total_seconds()
+ )
+ except concurrent.futures.TimeoutError:
+ raise TimeoutError(
+ f"MCP call timed out after "
+ f"{self.read_timeout_seconds.total_seconds()}"
+ f" seconds"
+ )
+
+ except RuntimeError as e:
+ # Only handle the specific "no running event loop" case
+ if (
+ "no running event loop" in str(e).lower()
+ or "no current event loop" in str(e).lower()
+ ):
+ # No event loop is running, we can safely use run_async
+ from camel.utils.commons import run_async
+
+ run_async_func = run_async(async_mcp_call)
+ return run_async_func(**kwargs)
+ else:
+ # Re-raise other RuntimeErrors
+ raise
+
+ # Add an async_call method to the function for explicit async usage
+ adaptive_dynamic_function.async_call = async_mcp_call # type: ignore[attr-defined]
+
+ adaptive_dynamic_function.__name__ = func_name
+ adaptive_dynamic_function.__doc__ = func_desc
+ adaptive_dynamic_function.__annotations__ = annotations
sig = inspect.Signature(
parameters=[
@@ -676,9 +743,9 @@ class MCPClient:
for param in func_params
]
)
- dynamic_function.__signature__ = sig # type: ignore[attr-defined]
+ adaptive_dynamic_function.__signature__ = sig # type: ignore[attr-defined]
- return dynamic_function
+ return adaptive_dynamic_function
def _build_tool_schema(self, mcp_tool: types.Tool) -> Dict[str, Any]:
r"""Build tool schema for OpenAI function calling format."""
diff --git a/docs/mintlify/reference/camel.toolkits.mcp_toolkit.mdx b/docs/mintlify/reference/camel.toolkits.mcp_toolkit.mdx
index bae11f6d6..d007e0127 100644
--- a/docs/mintlify/reference/camel.toolkits.mcp_toolkit.mdx
+++ b/docs/mintlify/reference/camel.toolkits.mcp_toolkit.mdx
@@ -81,6 +81,7 @@ manages multiple MCPClient instances using AsyncExitStack.
- **config_path** (Optional[str], optional): Path to a JSON configuration file defining MCP servers. The file should contain server configurations in the standard MCP format. (default: :obj:`None`)
- **config_dict** (Optional[Dict[str, Any]], optional): Dictionary containing MCP server configurations in the same format as the config file. This allows for programmatic configuration without file I/O. (default: :obj:`None`)
- **timeout** (Optional[float], optional): Timeout for connection attempts in seconds. This timeout applies to individual client connections. (default: :obj:`None`)
+- **strict** (Optional[bool], optional): Flag to indicate strict mode. (default: :obj:`False`)
- **Note**: At least one of :obj:`clients`, :obj:`config_path`, or :obj:`config_dict` must be provided. If multiple sources are provided, clients from all sources will be combined. For web servers in the config, you can specify authorization headers using the "headers" field to connect to protected MCP server endpoints. Example configuration: .. code-block:: json `{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"] }, "protected-server": { "url": "https://example.com/mcp", "timeout": 30, "headers": { "Authorization": "Bearer YOUR_TOKEN", "X-API-Key": "YOUR_API_KEY" } } } }`
- **Attributes**:
- **clients** (List[MCPClient]): List of :obj:`MCPClient` instances being managed by this toolkit.
@@ -95,7 +96,8 @@ def __init__(
clients: Optional[List[MCPClient]] = None,
config_path: Optional[str] = None,
config_dict: Optional[Dict[str, Any]] = None,
- timeout: Optional[float] = None
+ timeout: Optional[float] = None,
+ strict: Optional[bool] = False
):
```
@@ -167,7 +169,8 @@ def create_sync(
clients: Optional[List[MCPClient]] = None,
config_path: Optional[str] = None,
config_dict: Optional[Dict[str, Any]] = None,
- timeout: Optional[float] = None
+ timeout: Optional[float] = None,
+ strict: Optional[bool] = False
):
```
diff --git a/docs/mintlify/reference/camel.utils.mcp_client.mdx b/docs/mintlify/reference/camel.utils.mcp_client.mdx
index 055a5e94c..e2989266c 100644
--- a/docs/mintlify/reference/camel.utils.mcp_client.mdx
+++ b/docs/mintlify/reference/camel.utils.mcp_client.mdx
@@ -155,8 +155,8 @@ a given MCP tool.
**Returns:**
- Callable: A dynamically created async Python function that wraps
-the MCP tool.
+ Callable: A dynamically created Python function that wraps
+the MCP tool and works in both sync and async contexts.
<a id="camel.utils.mcp_client.MCPClient._build_tool_schema"></a>
diff --git a/examples/toolkits/mcp/mcp_toolkit.py b/examples/toolkits/mcp/mcp_toolkit.py
index 4f0ef234a..99586127d 100644
--- a/examples/toolkits/mcp/mcp_toolkit.py
+++ b/examples/toolkits/mcp/mcp_toolkit.py
@@ -112,6 +112,54 @@ async def mcp_toolkit_example():
print(response.info['tool_calls'])
+'''
+===============================================================================
+Here are 5 files in the project using relative paths:
+
+1. `.env`
+2. `.gitignore`
+3. `CONTRIBUTING.md`
+4. `LICENSE`
+5. `README.md`
+[ToolCallingRecord(tool_name='list_allowed_directories', args={},
+result='Allowed directories:\n/Users/enrei/Desktop/camel0605/camel',
+tool_call_id='call_xTidk11chOk8j9gjrpNMlKjq'), ToolCallingRecord
+(tool_name='list_directory', args={'path': '/Users/enrei/Desktop/camel0605/
+camel'}, result='[DIR] .container\n[FILE] .env\n[DIR] .git\n[DIR] .github\n
+[FILE] .gitignore\n[DIR] .mypy_cache\n[FILE] .pre-commit-config.yaml\n[DIR]
+pytest_cache\n[DIR] .ruff_cache\n[FILE] .style.yapf\n[DIR] .venv\n[FILE]
+CONTRIBUTING.md\n[FILE] LICENSE\n[FILE] Makefile\n[FILE] README.md\n[DIR]
+apps\n[DIR] camel\n[DIR] data\n[DIR] docs\n[DIR] examples\n[DIR] licenses\n
+[DIR] misc\n[FILE] pyproject.toml\n[DIR] services\n[DIR] test\n[FILE] uv.
+lock', tool_call_id='call_8eaZP8LQxxvM3cauWWyZ2fJ4')]
+===============================================================================
+'''
+
+
+# Same example as above but in sync mode
+def mcp_toolkit_example_sync():
+ # Use either config path or config dict to initialize the MCP toolkit.
+ config_path = Path(__file__).parent / "mcp_servers_config.json"
+
+ # Connect to all MCP servers.
+ with MCPToolkit(config_path=str(config_path)) as mcp_toolkit:
+ sys_msg = "You are a helpful assistant"
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEFAULT,
+ model_type=ModelType.DEFAULT,
+ )
+ camel_agent = ChatAgent(
+ system_message=sys_msg,
+ model=model,
+ tools=[*mcp_toolkit.get_tools()],
+ )
+ user_msg = "List 5 files in the project, using relative paths"
+ # response = await camel_agent.astep(user_msg)
+ response = camel_agent.step(user_msg)
+ print(response.msgs[0].content)
+ print(response.info['tool_calls'])
+
+
'''
===============================================================================
Here are 5 files in the project using relative paths:
@@ -124,7 +172,30 @@ Here are 5 files in the project using relative paths:
===============================================================================
'''
-
if __name__ == "__main__":
- asyncio.run(mcp_client_example())
+ # asyncio.run(mcp_client_example())
asyncio.run(mcp_toolkit_example())
+ # mcp_toolkit_example_sync()
+
+'''
+===============================================================================
+Here are 5 files in the project using relative paths:
+
+1. `.env`
+2. `.gitignore`
+3. `CONTRIBUTING.md`
+4. `LICENSE`
+5. `README.md`
+[ToolCallingRecord(tool_name='list_allowed_directories', args={},
+result='Allowed directories:\n/Users/enrei/Desktop/camel0605/camel',
+tool_call_id='call_xTidk11chOk8j9gjrpNMlKjq'), ToolCallingRecord
+(tool_name='list_directory', args={'path': '/Users/enrei/Desktop/camel0605/
+camel'}, result='[DIR] .container\n[FILE] .env\n[DIR] .git\n[DIR] .github\n
+[FILE] .gitignore\n[DIR] .mypy_cache\n[FILE] .pre-commit-config.yaml\n[DIR]
+pytest_cache\n[DIR] .ruff_cache\n[FILE] .style.yapf\n[DIR] .venv\n[FILE]
+CONTRIBUTING.md\n[FILE] LICENSE\n[FILE] Makefile\n[FILE] README.md\n[DIR]
+apps\n[DIR] camel\n[DIR] data\n[DIR] docs\n[DIR] examples\n[DIR] licenses\n
+[DIR] misc\n[FILE] pyproject.toml\n[DIR] services\n[DIR] test\n[FILE] uv.
+lock', tool_call_id='call_8eaZP8LQxxvM3cauWWyZ2fJ4')]
+===============================================================================
+'''