Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(tool): support tool-level onion middleware in ToolBase (#1754)
nuthalapativarun02d3912b78cb
diff --git a/src/agentscope/tool/__init__.py b/src/agentscope/tool/__init__.pyindex feac7fedb..1ca29b31c 100644--- a/src/agentscope/tool/__init__.py+++ b/src/agentscope/tool/__init__.py@@ -4,7 +4,7 @@from ._types import ToolChoice, Function, RegisteredToolfrom ._response import ToolResponse, ToolChunkfrom ._toolkit import Toolkit-from ._base import ToolBase, ParamsBase+from ._base import ToolBase, ParamsBase, ToolMiddlewareBasefrom ._adapters import MCPTool, FunctionToolfrom ._builtin import (ResetTools,@@ -29,6 +29,7 @@ __all__ = ["Function","ToolBase","ParamsBase",+ "ToolMiddlewareBase","MCPTool","FunctionTool","ToolGroup",diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.pyindex 65990238f..b2ba5357c 100644--- a/src/agentscope/tool/_adapters.py+++ b/src/agentscope/tool/_adapters.py@@ -11,7 +11,7 @@ from mcp import ClientSessionimport mcpfrom ._types import Function-from ._base import ToolBase+from ._base import ToolBase, ToolMiddlewareBasefrom ..permission import (PermissionBehavior,PermissionDecision,@@ -54,6 +54,7 @@ class FunctionTool(ToolBase):is_concurrency_safe: bool = True,is_read_only: bool = False,is_state_injected: bool = False,+ middlewares: list[ToolMiddlewareBase] | None = None,) -> None:"""Initialize the FunctionTool.@@ -70,7 +71,10 @@ class FunctionTool(ToolBase):Whether this tool only reads data without side effects.is_state_injected (`bool`, optional):Whether this tool requires agent state injection.+ middlewares (`list[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution."""+ super().__init__(middlewares=middlewares)self.name = name or func.__name__self.description = description or _extract_func_description(func.__doc__ or "",@@ -102,7 +106,7 @@ class FunctionTool(ToolBase):"by the user.",)- async def __call__(+ async def call(self,**kwargs: Any,) -> ToolChunk | AsyncGenerator[ToolChunk, None]:@@ -181,6 +185,7 @@ class MCPTool(ToolBase):| None = None,session: Any | None = None,timeout: float | None = None,+ middlewares: list[ToolMiddlewareBase] | None = None,) -> None:"""Initialize the MCPTool.@@ -198,7 +203,10 @@ class MCPTool(ToolBase):Either this or ``client_gen`` must be provided.timeout (`float | None`, optional):The timeout in seconds for tool execution.+ middlewares (`list[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution."""+ super().__init__(middlewares=middlewares)self.mcp_name = mcp_name# LLM providers enforce ^[a-zA-Z0-9_-]+$ on tool names.@@ -278,7 +286,7 @@ class MCPTool(ToolBase):message="MCP tools must be explicitly allowed by the user.",)- async def __call__(+ async def call(self,**kwargs: Any,) -> ToolChunk:diff --git a/src/agentscope/tool/_base.py b/src/agentscope/tool/_base.pyindex e7e44ce2e..93a80f304 100644--- a/src/agentscope/tool/_base.py+++ b/src/agentscope/tool/_base.py@@ -1,10 +1,11 @@# -*- coding: utf-8 -*-# pylint: disable=unused-argument"""The tool protocol in agentscope."""+import inspectimport osfrom abc import abstractmethod, ABCfrom pathlib import Path-from typing import AsyncGenerator, Any, List+from typing import AsyncGenerator, Any, Callable, Listfrom pydantic import BaseModel@@ -32,6 +33,64 @@ class ParamsBase(BaseModel):return _remove_title_field(super().model_json_schema(*args, **kwargs))+class ToolMiddlewareBase(ABC):+ """Base class for tool middlewares.++ A tool middleware wraps the execution of a tool in an onion fashion: the+ first registered middleware is the outermost layer and runs its pre-logic+ before any inner layer, then its post-logic after all inner layers have+ completed. Subclass this and implement :meth:`on_tool_call` — the signature+ is already spelled out, so second-party developers only need to fill in the+ body without reasoning about the wrapping protocol.++ Streaming and non-streaming tools are unified: ``next_handler`` always+ returns an async generator, so a middleware never needs to know whether the+ underlying tool yields a stream of chunks or returns a single chunk.++ Example:+ ```python+ class LoggingMiddleware(ToolMiddlewareBase):+ async def on_tool_call(self, tool, input_kwargs, next_handler):+ print(f"Calling {tool.name} with {input_kwargs}")+ async for chunk in next_handler(**input_kwargs):+ yield chunk+ print(f"Finished {tool.name}")++ tool = MyTool(middlewares=[LoggingMiddleware()])+ ```+ """++ @abstractmethod+ async def on_tool_call(+ self,+ tool: "ToolBase",+ input_kwargs: dict[str, Any],+ next_handler: Callable[..., AsyncGenerator[ToolChunk, None]],+ ) -> AsyncGenerator[ToolChunk, None]:+ """Intercept a single tool invocation.++ Add pre-/post-logic around ``next_handler``, rewrite the tool inputs by+ passing modified keyword arguments to ``next_handler``, or transform+ the yielded chunks.++ Args:+ tool (`ToolBase`):+ The tool instance being invoked.+ input_kwargs (`dict[str, Any]`):+ The tool's input arguments for this invocation. Pass them on+ via ``next_handler(**input_kwargs)``; mutate or replace them to+ change what the inner layers and the tool itself receive.+ next_handler (`Callable[..., AsyncGenerator[ToolChunk, None]]`):+ Call it as ``next_handler(**input_kwargs)`` to run the next+ layer. It always returns an async generator, regardless of+ whether the underlying tool is streaming or not.++ Yields:+ `ToolChunk`:+ The chunks produced by this tool invocation.+ """++class ToolBase(ABC):"""The tool protocol."""@@ -67,6 +126,127 @@ class ToolBase(ABC):"""List of dangerous directories that should be protected fromauto-editing."""+ def __init__(+ self,+ middlewares: List["ToolMiddlewareBase"] | None = None,+ ) -> None:+ """Initialize the tool with optional middlewares.++ Args:+ middlewares (`List[ToolMiddlewareBase] | None`, optional):+ A list of :class:`ToolMiddlewareBase` instances wrapping the+ tool execution in an onion fashion. Defaults to an empty list.+ """+ self._middlewares: List["ToolMiddlewareBase"] = (+ middlewares if middlewares is not None else []+ )++ async def call(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> ToolChunk | AsyncGenerator[ToolChunk, None]:+ """Execute the tool logic.++ This is the new override point for tool implementations.+ Subclasses should override this method instead of+ :meth:`__call__`. The base implementation raises+ :exc:`NotImplementedError` for non-external tools and+ :exc:`RuntimeError` for external tools.++ Args:+ **kwargs: Tool input arguments.++ Returns:+ `ToolChunk | AsyncGenerator[ToolChunk, None]`:+ A single :class:`~agentscope.tool.ToolChunk` or an+ async generator that yields them.+ """+ if not self.is_external_tool:+ raise NotImplementedError(+ f"{self.__class__.__name__} does not implement call",+ )++ raise RuntimeError(+ f"{self.__class__.__name__} is an external tool and should not "+ f"be called directly",+ )++ async def __call__(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> ToolChunk | AsyncGenerator[ToolChunk, None]:+ """Invoke the tool, layering any registered middlewares around+ :meth:`call`.++ Tools are always invoked with keyword arguments only. ``*args`` is+ accepted in the signature solely to stay Liskov-compatible with+ subclasses that override ``__call__`` with their own positional+ parameters; any positional argument actually passed here is rejected+ (raising :exc:`TypeError`) so it fails loudly instead of being silently+ dropped.++ Middlewares are applied in an onion fashion: the first registered+ middleware is the outermost layer and runs its pre-logic before+ any inner layers, then its post-logic after all inner layers+ have completed.+ """+ if args:+ raise TypeError(+ f"{type(self).__name__} must be called with keyword arguments "+ f"only, but got {len(args)} positional argument(s).",+ )+ # ``getattr`` with a default so the no-middleware path keeps working+ # even if a subclass overrides ``__init__`` without calling+ # ``super().__init__()``.+ middlewares = getattr(self, "_middlewares", [])+ if not middlewares:+ if inspect.isasyncgenfunction(self.call):+ return self.call(**kwargs)+ return await self.call(**kwargs)++ async def execute_chain(+ index: int = 0,+ **chain_kwargs: Any,+ ) -> AsyncGenerator[ToolChunk, None]:+ """Execute the tool middleware chain."""+ if index >= len(middlewares):+ # Innermost layer: run the tool's own ``call``. ``call`` is+ # always async but comes in two shapes — an async generator+ # function (e.g. ``Bash``) or a coroutine returning a single+ # ``ToolChunk`` / an async generator (e.g. ``FunctionTool``).+ # Normalize both into a single stream so middlewares never have+ # to distinguish them.+ if inspect.isasyncgenfunction(self.call):+ async for chunk in self.call(**chain_kwargs):+ yield chunk+ else:+ result = await self.call(**chain_kwargs)+ if isinstance(result, AsyncGenerator):+ async for chunk in result:+ yield chunk+ else:+ yield result+ else:+ mw = middlewares[index]+ input_kwargs = dict(chain_kwargs)++ async def next_handler(+ **kw: Any,+ ) -> AsyncGenerator[ToolChunk, None]:+ async for chunk in execute_chain(index + 1, **kw):+ yield chunk++ async for chunk in mw.on_tool_call(+ tool=self,+ input_kwargs=input_kwargs,+ next_handler=next_handler,+ ):+ yield chunk++ return execute_chain(**kwargs)+@abstractmethodasync def check_permissions(self,@@ -269,19 +449,3 @@ class ToolBase(ABC):return Truereturn False-- async def __call__(- self,- *args: Any,- **kwargs: Any,- ) -> ToolChunk | AsyncGenerator[ToolChunk, None]:- """Invoke the tool with the given arguments."""- if not self.is_external_tool:- raise NotImplementedError(- f"{self.__class__.__name__} does not implement __call__",- )-- raise RuntimeError(- f"{self.__class__.__name__} is an external tool and should not "- f"be called directly",- )diff --git a/src/agentscope/tool/_builtin/_bash.py b/src/agentscope/tool/_builtin/_bash.pyindex 029fc9795..96cb7275a 100644--- a/src/agentscope/tool/_builtin/_bash.py+++ b/src/agentscope/tool/_builtin/_bash.py@@ -6,7 +6,7 @@ import reimport asynciofrom ._bash_parser import BashCommandParser-from .._base import ToolBase+from .._base import ToolBase, ToolMiddlewareBasefrom .._constants import (DEFAULT_DANGEROUS_FILES,DEFAULT_DANGEROUS_DIRECTORIES,@@ -155,6 +155,7 @@ easier to review tool calls and give permission.dangerous_files: list[str] = DEFAULT_DANGEROUS_FILES,dangerous_directories: list[str] = DEFAULT_DANGEROUS_DIRECTORIES,cwd: str | os.PathLike[str] | None = None,+ middlewares: List[ToolMiddlewareBase] | None = None,) -> None:"""Initialize the bash tool.@@ -174,8 +175,11 @@ easier to review tool calls and give permission.directory check.cwd (`str | os.PathLike[str] | None`, optional):The working directory used when executing bash commands.+ middlewares (`List[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution."""+ super().__init__(middlewares=middlewares)self._bash_parser = BashCommandParser()self.dangerous_files = list(dangerous_files)@@ -663,7 +667,7 @@ easier to review tool calls and give permission.return False- async def __call__( # type: ignore[override]+ async def call( # type: ignore[override] # pylint: disable=unused-argumentself,command: str,description: str = "",diff --git a/src/agentscope/tool/_builtin/_edit.py b/src/agentscope/tool/_builtin/_edit.pyindex eb5bc4387..caa79ae53 100644--- a/src/agentscope/tool/_builtin/_edit.py+++ b/src/agentscope/tool/_builtin/_edit.py@@ -6,7 +6,7 @@ from typing import Any, Listimport aiofiles-from .._base import ToolBase+from .._base import ToolBase, ToolMiddlewareBasefrom .._constants import (DEFAULT_DANGEROUS_FILES,DEFAULT_DANGEROUS_DIRECTORIES,@@ -89,6 +89,7 @@ Usage:self,dangerous_files: list[str] = DEFAULT_DANGEROUS_FILES,dangerous_directories: list[str] = DEFAULT_DANGEROUS_DIRECTORIES,+ middlewares: List[ToolMiddlewareBase] | None = None,) -> None:"""Initialize the edit tool.@@ -106,7 +107,10 @@ Usage:`DEFAULT_DANGEROUS_DIRECTORIES`. Pass a custom list tofully replace the defaults, or `[]` to disable thedirectory check.+ middlewares (`List[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution."""+ super().__init__(middlewares=middlewares)self.dangerous_files = list(dangerous_files)self.dangerous_directories = list(dangerous_directories)@@ -232,7 +236,7 @@ Usage:),]- async def __call__( # type: ignore[override]+ async def call( # type: ignore[override]self,file_path: str,old_string: str,diff --git a/src/agentscope/tool/_builtin/_glob.py b/src/agentscope/tool/_builtin/_glob.pyindex 5ea038de3..80c3d1bdc 100644--- a/src/agentscope/tool/_builtin/_glob.py+++ b/src/agentscope/tool/_builtin/_glob.py@@ -5,7 +5,7 @@ import osimport refrom typing import Any, List-from .._base import ToolBase+from .._base import ToolBase, ToolMiddlewareBasefrom ...permission import (PermissionContext,PermissionDecision,@@ -55,8 +55,17 @@ codebase.""" # ignore: E501is_external_tool: bool = Falseis_state_injected: bool = False- def __init__(self) -> None:- """Initialize the glob tool."""+ def __init__(+ self,+ middlewares: List[ToolMiddlewareBase] | None = None,+ ) -> None:+ """Initialize the glob tool.++ Args:+ middlewares (`List[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution.+ """+ super().__init__(middlewares=middlewares)async def check_permissions(self,@@ -263,7 +272,7 @@ codebase.""" # ignore: E501self.match_parts(parts, 0, base_dir, results)return results- async def __call__( # type: ignore[override]+ async def call( # type: ignore[override]self,pattern: str,path: str | None = None,diff --git a/src/agentscope/tool/_builtin/_grep.py b/src/agentscope/tool/_builtin/_grep.pyindex 1ec2b1fec..a142deefc 100644--- a/src/agentscope/tool/_builtin/_grep.py+++ b/src/agentscope/tool/_builtin/_grep.py@@ -6,7 +6,7 @@ import osimport shutilfrom typing import Any, List, Literal-from .._base import ToolBase+from .._base import ToolBase, ToolMiddlewareBasefrom ..._logging import loggerfrom ...permission import (PermissionContext,@@ -157,8 +157,17 @@ class Grep(ToolBase):is_external_tool: bool = Falseis_state_injected: bool = False- def __init__(self) -> None:- """Initialize the grep tool."""+ def __init__(+ self,+ middlewares: List[ToolMiddlewareBase] | None = None,+ ) -> None:+ """Initialize the grep tool.++ Args:+ middlewares (`List[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution.+ """+ super().__init__(middlewares=middlewares)self._rg_path = shutil.which("rg")if self._rg_path is None:logger.warning(@@ -304,7 +313,7 @@ class Grep(ToolBase):]return lines- async def __call__( # type: ignore[override]+ async def call( # type: ignore[override]self,pattern: str,path: str | None = None,diff --git a/src/agentscope/tool/_builtin/_meta.py b/src/agentscope/tool/_builtin/_meta.pyindex b3fccff41..fe0fecfe8 100644--- a/src/agentscope/tool/_builtin/_meta.py+++ b/src/agentscope/tool/_builtin/_meta.py@@ -1,6 +1,6 @@# -*- coding: utf-8 -*-"""The meta tool class."""-from typing import Any+from typing import Any, Listfrom pydantic import Field, create_modelfrom jinja2 import Template@@ -12,7 +12,7 @@ from ...permission import (PermissionBehavior,)from .._response import ToolChunk-from .._base import ToolBase+from .._base import ToolBase, ToolMiddlewareBasefrom ...exception import DeveloperOrientedExceptionfrom ...message import TextBlockfrom ...state import AgentState@@ -49,8 +49,10 @@ class ResetTools(ToolBase):self,groups: list[ToolGroup],response_template: str,+ middlewares: List[ToolMiddlewareBase] | None = None,) -> None:"""Initialize the meta tool with the current tool groups."""+ super().__init__(middlewares=middlewares)self.groups = groupsself.response_template = response_template@@ -85,7 +87,7 @@ class ResetTools(ToolBase):message="The meta tool is always allowed to be called.",)- async def __call__(+ async def call(self,_agent_state: AgentState,**kwargs: Any,diff --git a/src/agentscope/tool/_builtin/_read.py b/src/agentscope/tool/_builtin/_read.pyindex 0796cd66f..d5087e5dd 100644--- a/src/agentscope/tool/_builtin/_read.py+++ b/src/agentscope/tool/_builtin/_read.py@@ -6,7 +6,7 @@ from typing import Any, Listimport aiofiles-from .._base import ToolBase+from .._base import ToolBase, ToolMiddlewareBasefrom ...permission import (PermissionContext,PermissionDecision,@@ -72,6 +72,7 @@ Usage:def __init__(self,max_line_characters: int = 2000,+ middlewares: List[ToolMiddlewareBase] | None = None,) -> None:"""Initialize the read tool.@@ -82,8 +83,10 @@ Usage:a "[truncated]" suffix. This prevents overwhelming the agentwith excessively long lines while still providing usefulcontent.+ middlewares (`List[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution."""-+ super().__init__(middlewares=middlewares)self._max_line_characters = max_line_charactersasync def check_permissions(@@ -167,7 +170,7 @@ Usage:),]- async def __call__( # type: ignore[override]+ async def call( # type: ignore[override]self,file_path: str,offset: int = 1,diff --git a/src/agentscope/tool/_builtin/_skill.py b/src/agentscope/tool/_builtin/_skill.pyindex 825a625bb..44e7055dd 100644--- a/src/agentscope/tool/_builtin/_skill.py+++ b/src/agentscope/tool/_builtin/_skill.py@@ -1,6 +1,6 @@# -*- coding: utf-8 -*-"""The builtin skill viewer tool."""-from typing import Any, Callable, Awaitable+from typing import Any, Callable, Awaitable, Listfrom ...exception import DeveloperOrientedExceptionfrom ...permission import (@@ -9,7 +9,7 @@ from ...permission import (PermissionBehavior,)from .._response import ToolChunk-from .._base import ToolBase+from .._base import ToolBase, ToolMiddlewareBasefrom ...skill import Skillfrom ...message import TextBlock, ToolResultStatefrom ...state import AgentState@@ -63,13 +63,17 @@ class SkillViewer(ToolBase):def __init__(self,get_skills_method: Callable[..., Awaitable[dict[str, Skill]]],+ middlewares: List[ToolMiddlewareBase] | None = None,) -> None:"""Initialize the skill viewer with the list of skills.Args:get_skills_method (`Callable[..., dict[str, Skill]]`):An async method that returns the current skills of the agent.+ middlewares (`List[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution."""+ super().__init__(middlewares=middlewares)self._get_skills_method = get_skills_methodasync def check_permissions(@@ -83,7 +87,7 @@ class SkillViewer(ToolBase):message="The skill viewer is always allowed to be called.",)- async def __call__(+ async def call(self,skill: str,_agent_state: AgentState,diff --git a/src/agentscope/tool/_builtin/_write.py b/src/agentscope/tool/_builtin/_write.pyindex 64a6f05f3..7e162738f 100644--- a/src/agentscope/tool/_builtin/_write.py+++ b/src/agentscope/tool/_builtin/_write.py@@ -7,7 +7,7 @@ from typing import Any, Listimport aiofiles-from .._base import ToolBase+from .._base import ToolBase, ToolMiddlewareBasefrom .._constants import (DEFAULT_DANGEROUS_FILES,DEFAULT_DANGEROUS_DIRECTORIES,@@ -67,6 +67,7 @@ Usage:self,dangerous_files: list[str] = DEFAULT_DANGEROUS_FILES,dangerous_directories: list[str] = DEFAULT_DANGEROUS_DIRECTORIES,+ middlewares: List[ToolMiddlewareBase] | None = None,) -> None:"""Initialize the write tool.@@ -84,7 +85,10 @@ Usage:`DEFAULT_DANGEROUS_DIRECTORIES`. Pass a custom list tofully replace the defaults, or `[]` to disable thedirectory check.+ middlewares (`List[ToolMiddlewareBase] | None`, optional):+ Tool middlewares wrapping the tool execution."""+ super().__init__(middlewares=middlewares)self.dangerous_files = list(dangerous_files)self.dangerous_directories = list(dangerous_directories)@@ -210,7 +214,7 @@ Usage:),]- async def __call__( # type: ignore[override]+ async def call( # type: ignore[override]self,file_path: str,content: str,diff --git a/src/agentscope/tool/_task/_create_task.py b/src/agentscope/tool/_task/_create_task.pyindex 7531e23f1..2dc165e94 100644--- a/src/agentscope/tool/_task/_create_task.py+++ b/src/agentscope/tool/_task/_create_task.py@@ -80,7 +80,7 @@ All tasks are created with status `pending`.input_schema: dict = _TaskCreateParams.model_json_schema()- async def __call__(+ async def call(self,_agent_state: AgentState,subject: str,diff --git a/src/agentscope/tool/_task/_get_task.py b/src/agentscope/tool/_task/_get_task.pyindex 978a16d69..82936e251 100644--- a/src/agentscope/tool/_task/_get_task.py+++ b/src/agentscope/tool/_task/_get_task.py@@ -44,7 +44,7 @@ Returns full task details:input_schema: dict = _TaskGetParams.model_json_schema()- async def __call__(+ async def call(self,task_id: str,_agent_state: AgentState,diff --git a/src/agentscope/tool/_task/_list_task.py b/src/agentscope/tool/_task/_list_task.pyindex c1164fd3b..38f1565d3 100644--- a/src/agentscope/tool/_task/_list_task.py+++ b/src/agentscope/tool/_task/_list_task.py@@ -41,7 +41,7 @@ Use TaskGet with a specific task ID to view full details including description ainput_schema: dict = _TaskListParams.model_json_schema()- async def __call__(self, _agent_state: AgentState) -> ToolChunk:+ async def call(self, _agent_state: AgentState) -> ToolChunk:"""List tasks for the agent to perform."""if not isinstance(_agent_state, AgentState):# Expose error to the developerdiff --git a/src/agentscope/tool/_task/_update_task.py b/src/agentscope/tool/_task/_update_task.pyindex 7f4a95b71..abdf11d45 100644--- a/src/agentscope/tool/_task/_update_task.py+++ b/src/agentscope/tool/_task/_update_task.py@@ -132,7 +132,7 @@ Set up task dependencies:input_schema: dict = _TaskUpdateParams.model_json_schema()- async def __call__(+ async def call(self,_agent_state: AgentState,task_id: str,diff --git a/tests/builtin_bash_test.py b/tests/builtin_bash_test.pyindex 5e807c303..a42f530af 100644--- a/tests/builtin_bash_test.py+++ b/tests/builtin_bash_test.py@@ -47,7 +47,7 @@ class BashCwdTest(IsolatedAsyncioTestCase):create_process,):chunks = []- async for chunk in Bash(cwd="workspace")(command="pwd"):+ async for chunk in await Bash(cwd="workspace")(command="pwd"):chunks.append(chunk)self.assertEqual(create_process.call_args.kwargs["cwd"], "workspace")@@ -86,7 +86,7 @@ class BashToolTest(IsolatedAsyncioTestCase):async def test_simple_command(self) -> None:"""Test executing a simple bash command."""chunks = []- async for chunk in self.bash_tool(command="echo 'Hello World'"):+ async for chunk in await self.bash_tool(command="echo 'Hello World'"):chunks.append(chunk)self.assertEqual(len(chunks), 1)@@ -100,7 +100,7 @@ class BashToolTest(IsolatedAsyncioTestCase):async def test_command_with_error(self) -> None:"""Test executing a command that fails."""chunks = []- async for chunk in self.bash_tool(command="exit 1"):+ async for chunk in await self.bash_tool(command="exit 1"):chunks.append(chunk)self.assertEqual(len(chunks), 1)@@ -114,7 +114,7 @@ class BashToolTest(IsolatedAsyncioTestCase):async def test_command_timeout(self) -> None:"""Test command timeout."""chunks = []- async for chunk in self.bash_tool(+ async for chunk in await self.bash_tool(command="sleep 10",timeout=100, # 100ms timeout):diff --git a/tests/tool_middleware_test.py b/tests/tool_middleware_test.pynew file mode 100644index 000000000..c9e83fab8--- /dev/null+++ b/tests/tool_middleware_test.py@@ -0,0 +1,344 @@+# -*- coding: utf-8 -*-+# pylint: disable=unused-argument+"""Test cases for the tool-level onion middleware mechanism."""+from typing import Any, AsyncGenerator+from unittest.async_case import IsolatedAsyncioTestCase++from utils import AnyString++from agentscope.tool import (+ ToolBase,+ ToolMiddlewareBase,+ ToolChunk,+)+from agentscope.message import TextBlock, ToolResultState+from agentscope.permission import (+ PermissionDecision,+ PermissionBehavior,+)+++def _expected_chunk(text: str) -> dict:+ """Build the full expected ``ToolChunk.model_dump()`` dict for the given+ text, with random ``id`` fields matched by :class:`AnyString`."""+ return {+ "content": [{"type": "text", "text": text, "id": AnyString()}],+ "state": ToolResultState.RUNNING,+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ }+++class _NonStreamingTool(ToolBase):+ """A tool whose ``call`` returns a single ToolChunk (coroutine)."""++ name: str = "non_streaming_tool"+ description: str = "A tool that returns a single chunk."+ input_schema: dict = {"type": "object", "properties": {}}+ is_concurrency_safe: bool = True+ is_read_only: bool = True+ is_mcp: bool = False++ async def check_permissions(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> PermissionDecision:+ """Check permissions for the tool."""+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message="allowed",+ )++ async def call(self, **kwargs: Any) -> ToolChunk:+ """Run the tool, echoing back the received kwargs."""+ return ToolChunk(+ content=[TextBlock(text=f"call() kwargs={kwargs}")],+ )+++class _StreamingTool(ToolBase):+ """A tool whose ``call`` is an async generator function."""++ name: str = "streaming_tool"+ description: str = "A tool that yields several chunks."+ input_schema: dict = {"type": "object", "properties": {}}+ is_concurrency_safe: bool = True+ is_read_only: bool = True+ is_mcp: bool = False++ async def check_permissions(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> PermissionDecision:+ """Check permissions for the tool."""+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message="allowed",+ )++ async def call(+ self,+ n: int = 2,+ **kwargs: Any,+ ) -> AsyncGenerator[ToolChunk, None]:+ """Yield ``n`` chunks."""+ for i in range(n):+ yield ToolChunk(content=[TextBlock(text=f"chunk-{i}")])+++class _NoSuperInitTool(ToolBase):+ """A tool that overrides ``__init__`` without calling ``super().__init__``.++ Used to verify the no-middleware path still works (via the ``getattr``+ fallback for ``_middlewares``).+ """++ name: str = "no_super_init_tool"+ description: str = "A tool that skips super().__init__()."+ input_schema: dict = {"type": "object", "properties": {}}+ is_concurrency_safe: bool = True+ is_read_only: bool = True+ is_mcp: bool = False++ def __init__(self) -> None: # pylint: disable=super-init-not-called+ """Intentionally does not call ``super().__init__()``."""+ self.marker = "initialized"++ async def check_permissions(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> PermissionDecision:+ """Check permissions for the tool."""+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message="allowed",+ )++ async def call(self, **kwargs: Any) -> ToolChunk:+ """Run the tool."""+ return ToolChunk(content=[TextBlock(text="no super init")])+++def _make_recording_middleware(+ label: str,+ execution_order: list[str],+) -> ToolMiddlewareBase:+ """Build a middleware that records pre/post markers in ``execution_order``+ and transparently forwards the chunks."""++ class _Middleware(ToolMiddlewareBase):+ async def on_tool_call(+ self,+ tool: Any,+ input_kwargs: dict,+ next_handler: Any,+ ) -> AsyncGenerator:+ execution_order.append(f"{label}-pre")+ async for chunk in next_handler(**input_kwargs):+ yield chunk+ execution_order.append(f"{label}-post")++ return _Middleware()+++class ToolMiddlewareTest(IsolatedAsyncioTestCase):+ """Tests for the tool-level onion middleware mechanism."""++ async def _drain(self, result: Any) -> list[dict]:+ """Collect all chunks from a middleware-wrapped ``__call__`` result,+ returning their full ``model_dump()`` dicts for whole-object asserts.+ """+ chunks = []+ async for chunk in result:+ chunks.append(chunk.model_dump())+ return chunks++ async def test_no_middleware_non_streaming(self) -> None:+ """A non-streaming tool with no middleware returns a single chunk."""+ tool = _NonStreamingTool()+ result = await tool()+ self.assertIsInstance(result, ToolChunk)+ self.assertEqual(+ result.model_dump(),+ _expected_chunk("call() kwargs={}"),+ )++ async def test_no_middleware_streaming(self) -> None:+ """A streaming tool with no middleware yields its chunks directly."""+ tool = _StreamingTool()+ result = await tool(n=3)+ chunks = await self._drain(result)+ self.assertEqual(+ chunks,+ [+ _expected_chunk("chunk-0"),+ _expected_chunk("chunk-1"),+ _expected_chunk("chunk-2"),+ ],+ )++ async def test_middleware_wraps_call_in_onion_order(self) -> None:+ """Two middlewares wrap call() in the correct onion order.++ Execution order must be:+ outer-pre -> inner-pre -> call() -> inner-post -> outer-post.+ """+ execution_order: list[str] = []+ tool = _NonStreamingTool(+ middlewares=[+ _make_recording_middleware("outer", execution_order),+ _make_recording_middleware("inner", execution_order),+ ],+ )++ chunks = await self._drain(await tool())++ self.assertEqual(chunks, [_expected_chunk("call() kwargs={}")])+ self.assertEqual(+ execution_order,+ ["outer-pre", "inner-pre", "inner-post", "outer-post"],+ )++ async def test_single_middleware(self) -> None:+ """A single middleware fires pre and post around call()."""+ execution_order: list[str] = []+ tool = _NonStreamingTool(+ middlewares=[_make_recording_middleware("only", execution_order)],+ )++ chunks = await self._drain(await tool())++ self.assertEqual(chunks, [_expected_chunk("call() kwargs={}")])+ self.assertEqual(execution_order, ["only-pre", "only-post"])++ async def test_middleware_with_streaming_tool(self) -> None:+ """Middleware transparently forwards each chunk of a streaming tool."""+ execution_order: list[str] = []+ tool = _StreamingTool(+ middlewares=[_make_recording_middleware("mw", execution_order)],+ )++ chunks = await self._drain(await tool(n=3))++ self.assertEqual(+ chunks,+ [+ _expected_chunk("chunk-0"),+ _expected_chunk("chunk-1"),+ _expected_chunk("chunk-2"),+ ],+ )+ self.assertEqual(execution_order, ["mw-pre", "mw-post"])++ async def test_middleware_can_rewrite_input_kwargs(self) -> None:+ """A middleware can mutate input_kwargs so the tool sees new args."""++ class _RewriteMiddleware(ToolMiddlewareBase):+ async def on_tool_call(+ self,+ tool: Any,+ input_kwargs: dict,+ next_handler: Any,+ ) -> AsyncGenerator:+ input_kwargs["injected"] = "value"+ async for chunk in next_handler(**input_kwargs):+ yield chunk++ tool = _NonStreamingTool(middlewares=[_RewriteMiddleware()])+ chunks = await self._drain(await tool(original="x"))++ self.assertEqual(+ chunks,+ [+ _expected_chunk(+ "call() kwargs={'original': 'x', 'injected': 'value'}",+ ),+ ],+ )++ async def test_middleware_can_transform_chunks(self) -> None:+ """A middleware can transform the chunks yielded by the tool."""++ class _UppercaseMiddleware(ToolMiddlewareBase):+ async def on_tool_call(+ self,+ tool: Any,+ input_kwargs: dict,+ next_handler: Any,+ ) -> AsyncGenerator:+ async for chunk in next_handler(**input_kwargs):+ yield ToolChunk(+ content=[+ TextBlock(text=chunk.content[0].text.upper()),+ ],+ )++ tool = _StreamingTool(middlewares=[_UppercaseMiddleware()])+ chunks = await self._drain(await tool(n=2))++ self.assertEqual(+ chunks,+ [_expected_chunk("CHUNK-0"), _expected_chunk("CHUNK-1")],+ )++ async def test_middleware_can_short_circuit(self) -> None:+ """A middleware that never calls next_handler skips the tool."""+ called = {"value": False}++ class _ShortCircuitTool(_NonStreamingTool):+ async def call(self, **kwargs: Any) -> ToolChunk:+ called["value"] = True+ return await super().call(**kwargs)++ class _ShortCircuitMiddleware(ToolMiddlewareBase):+ async def on_tool_call(+ self,+ tool: Any,+ input_kwargs: dict,+ next_handler: Any,+ ) -> AsyncGenerator:+ yield ToolChunk(content=[TextBlock(text="short-circuited")])++ tool = _ShortCircuitTool(middlewares=[_ShortCircuitMiddleware()])+ chunks = await self._drain(await tool())++ self.assertFalse(called["value"])+ self.assertEqual(chunks, [_expected_chunk("short-circuited")])++ async def test_middleware_exception_propagates(self) -> None:+ """An exception raised in a middleware propagates to the caller."""++ class _BoomMiddleware(ToolMiddlewareBase):+ async def on_tool_call(+ self,+ tool: Any,+ input_kwargs: dict,+ next_handler: Any,+ ) -> AsyncGenerator:+ raise ValueError("boom")+ yield # pylint: disable=unreachable++ tool = _NonStreamingTool(middlewares=[_BoomMiddleware()])++ with self.assertRaises(ValueError):+ await self._drain(await tool())++ async def test_positional_args_rejected(self) -> None:+ """Calling a tool with positional args raises TypeError instead of+ silently dropping them."""+ tool = _NonStreamingTool()+ with self.assertRaises(TypeError):+ await tool("positional") # type: ignore[call-arg]++ async def test_missing_super_init_no_middleware(self) -> None:+ """A tool that skips super().__init__() still works on the+ no-middleware path via the getattr fallback for _middlewares."""+ tool = _NoSuperInitTool()+ self.assertFalse(hasattr(tool, "_middlewares"))+ result = await tool()+ self.assertIsInstance(result, ToolChunk)+ self.assertEqual(result.model_dump(), _expected_chunk("no super init"))diff --git a/tests/toolkit_test.py b/tests/toolkit_test.pyindex e7c17499c..45388b36e 100644--- a/tests/toolkit_test.py+++ b/tests/toolkit_test.py@@ -54,7 +54,7 @@ class Tool1(ToolBase):message="Do you want to use my_tool?",)- async def __call__(self, **kwargs: Any) -> ToolChunk:+ async def call(self, **kwargs: Any) -> ToolChunk:"""Run the tool."""return ToolChunk(content=[TextBlock(text="Hello, world!")],@@ -85,7 +85,7 @@ class Tool2(ToolBase):message="Do you want to use my_tool?",)- async def __call__(self, **kwargs: Any) -> AsyncGenerator[ToolChunk, None]:+ async def call(self, **kwargs: Any) -> AsyncGenerator[ToolChunk, None]:"""Run the tool."""yield ToolChunk(content=[TextBlock(text="123", id="a")],