Hello !
I would like to sharing a small middleware I’ve been using to harden agents against malformed tool calls.
ToolArgsValidationMiddleware validates LLM-generated tool-call arguments against each tool’s schema before the tool runs — and before any HITL approval. Invalid args → error ToolMessages → model re-invoked to self-correct, all within the model node, so only the final valid AIMessage enters state.
from langchain.agents import create_agent
from langchain_tool_args_validation_middleware import ToolArgsValidationMiddleware
agent = create_agent(model, tools=tools, middleware=[ToolArgsValidationMiddleware()])
- Pydantic (
model_validate) and MCP / dict-schema (jsonschema) tools both supported automatically; unknown tools pass through. - Correct multi-call batch handling — every
tool_callgets a matchingToolMessage; valid siblings get a “not executed” notice and the model re-issues the corrected batch. strip_empty_valuesremoves spuriousnull/{}/[], writing cleaned args back so validation == execution.- Pluggable
extra_validatorsfor domain rules (bundled example flags LangChain internallc_<uuid>IDs that models sometimes pass as real data). - Configurable retries and fail-open / fail-raise.
Repo: GitHub - Serjbory/langchain-tool-args-validation-middleware: A LangChain agent middleware that validates LLM-generated tool-call arguments against each tool's schema before the tool runs (and before any human-in-the-loop approval step) · GitHub · pip install langchain-tool-args-validation-middleware
Would love feedback on how this should sit alongside the retry middlewares, and whether the fail-open default is the right call.
