add_tool_middleware
add_tool_middleware
Run middleware around every tool call, after any middleware added before it.
Middleware runs before the handler and calls call_next(args, raw_data) to run the
rest of the chain and the handler, possibly with changed arguments. What it returns
is the call’s result: the handler’s, a changed one, or its own without calling
call_next, as a FunctionResult or a dict.
- Agent-wide middleware runs outside a tool’s own
middleware=fromdefine_tool(). - Middleware that raises
ToolRefusaldeclines the call. Any other exception gives the model the unknown-outcome result, as a handler that raises does. - It covers tools defined with
define_tool(), not DataMap or native tools, which run on the platform. - For an
async defhandler,call_nextreturns an awaitable. Anasync defmiddleware canawait resolve(call_next(args, raw_data)), withresolvefromsignalwire.core.tool_middleware, to take either. - Synchronous handlers for different calls run at once in worker threads, so guard any shared state.
The retry dedupe from set_tool_resend_dedupe() runs
first, before any middleware.
Parameters
middleware
Called as middleware(name, args, raw_data, call_next).
name— the tool’s name.args— the parsed arguments.raw_data— the SWAIG request.call_next— runs the rest of the chain and the handler when called ascall_next(args, raw_data).
ToolMiddleware and CallNext are type aliases in
signalwire.core.tool_middleware.
Returns
AgentBase — Self for method chaining.