Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(mcp): support execution timeout for MCP tools (#1176)
DavdGao7cc368aa3b6b
diff --git a/src/agentscope/mcp/_http_stateless_client.py b/src/agentscope/mcp/_http_stateless_client.pyindex 0a0f3fc16..c90f965df 100644--- a/src/agentscope/mcp/_http_stateless_client.py+++ b/src/agentscope/mcp/_http_stateless_client.py@@ -93,6 +93,7 @@ class HttpStatelessClient(MCPClientBase):self,func_name: str,wrap_tool_result: bool = True,+ execution_timeout: float | None = None,) -> Callable[..., Awaitable[mcp.types.CallToolResult | ToolResponse]]:"""Get a tool function by its name.@@ -103,6 +104,8 @@ class HttpStatelessClient(MCPClientBase):Whether to wrap the tool result into agentscope's`ToolResponse` object. If `False`, the raw result type`mcp.types.CallToolResult` will be returned.+ execution_timeout (`float | None`, optional):+ The preset timeout in seconds for calling the tool function.Returns:`Callable[..., Awaitable[mcp.types.CallToolResult | \@@ -130,6 +133,7 @@ class HttpStatelessClient(MCPClientBase):tool=target_tool,wrap_tool_result=wrap_tool_result,client_gen=self.get_client,+ timeout=execution_timeout,)async def list_tools(self) -> List[mcp.types.Tool]:diff --git a/src/agentscope/mcp/_mcp_function.py b/src/agentscope/mcp/_mcp_function.pyindex a0bf1fefe..83701399b 100644--- a/src/agentscope/mcp/_mcp_function.py+++ b/src/agentscope/mcp/_mcp_function.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-"""The MCP tool function class in AgentScope."""from contextlib import _AsyncGeneratorContextManager+from datetime import timedeltafrom typing import Any, Callableimport mcp@@ -31,6 +32,7 @@ class MCPToolFunction:client_gen: Callable[..., _AsyncGeneratorContextManager[Any]]| None = None,session: ClientSession | None = None,+ timeout: float | None = None,) -> None:"""Initialize the MCP function."""self.mcp_name = mcp_name@@ -39,6 +41,11 @@ class MCPToolFunction:self.json_schema = _extract_json_schema_from_mcp_tool(tool)self.wrap_tool_result = wrap_tool_result+ if timeout:+ self.timeout = timedelta(timeout)+ else:+ self.timeout = None+# Cannot be None at the same timeif (client_gen is None@@ -66,12 +73,14 @@ class MCPToolFunction:res = await session.call_tool(self.name,arguments=kwargs,+ read_timeout_seconds=self.timeout,)else:res = await self.session.call_tool(self.name,arguments=kwargs,+ read_timeout_seconds=self.timeout,)if self.wrap_tool_result:diff --git a/src/agentscope/mcp/_stateful_client_base.py b/src/agentscope/mcp/_stateful_client_base.pyindex d88e5b69b..03c96db41 100644--- a/src/agentscope/mcp/_stateful_client_base.py+++ b/src/agentscope/mcp/_stateful_client_base.py@@ -113,6 +113,7 @@ class StatefulClientBase(MCPClientBase, ABC):self,func_name: str,wrap_tool_result: bool = True,+ execution_timeout: float | None = None,) -> MCPToolFunction:"""Get an async tool function from the MCP server by its name, sothat you can call it directly, wrap it into your own function, or@@ -128,6 +129,8 @@ class StatefulClientBase(MCPClientBase, ABC):Whether to wrap the tool result into agentscope's`ToolResponse` object. If `False`, the raw result type`mcp.types.CallToolResult` will be returned.+ execution_timeout (`float | None`, optional):+ The preset timeout in seconds for calling the tool function.Returns:`MCPToolFunction`:@@ -155,6 +158,7 @@ class StatefulClientBase(MCPClientBase, ABC):tool=target_tool,wrap_tool_result=wrap_tool_result,session=self.session,+ timeout=execution_timeout,)def _validate_connection(self) -> None:diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex ac7f9f99a..decc4dff9 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -19,6 +19,7 @@ from typing import (Awaitable,)+import mcpimport shortuuidfrom pydantic import (BaseModel,@@ -711,6 +712,16 @@ Check "{dir}/SKILL.md" for how to use this skill"""# Sync functionres = tool_func.original_func(**kwargs)+ except mcp.shared.exceptions.McpError as e:+ res = ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Error occurred when calling MCP tool: {e}",+ ),+ ],+ )+except Exception as e:res = ToolResponse(content=[