Create middleware that patches dangling tool calls in the messages history.
When an AI message contains tool_calls but subsequent messages don't include the corresponding ToolMessage responses, this middleware adds synthetic ToolMessages saying the tool call was cancelled.
This middleware patches in two places:
beforeAgent: Patches state at the start of the agent loop (handles most cases)wrapModelCall: Patches the request right before model invocation (handles
edge cases like HITL rejection during graph resume where state updates from
beforeAgent may not be applied in time)createPatchToolCallsMiddleware(
): AgentMiddleware<undefined, undefined, unknown, readonly ClientTool | ServerTool[]>import { createAgent } from "langchain";
import { createPatchToolCallsMiddleware } from "./middleware/patch_tool_calls";
const agent = createAgent({
model: "claude-sonnet-4-5-20250929",
middleware: [createPatchToolCallsMiddleware()],
});