DEV Community

Davi
Davi

Posted on Originally published at blog.mago.team

The Agentic TOCTOU Gap: How Multi-Step Tool Calls Create Exploitable Race Windows

An agent checks a file's hash before processing it. Three tool calls and one sub-agent handoff later, it processes a different file and never knows.

AI agents validate preconditions at tool-call time. In multi-step tasks, the gap between validation and execution spans network calls, sub-agent handoffs, and MCP server boundaries. The agentic TOCTOU window is orders of magnitude wider than OS filesystem races. It requires no timing precision to exploit, and no production framework closes it atomically today.

Agentic TOCTOU Is Structurally Different From OS Race Conditions

In classic TOCTOU, a process checks file permissions; the attacker swaps the file between check and access. Window: microseconds. Requires precise timing, often with kernel-level coordination.

In agentic TOCTOU, the agent checks a precondition such as "does the user have sufficient balance?" then executes "initiate the transfer." Between check and action: multiple network round-trips, possible sub-agent handoffs, MCP server calls, and model inference wait time. Window: seconds to minutes. No timing precision required.

Any attacker who can modify external state has an exploitable window after the check returns and before the action executes. No thread scheduler control is needed. No kernel access required. A writable shared resource and knowledge of the step sequence are sufficient.

Lilienthal and Hong (arXiv:2508.17155, TOCTOU-Bench) evaluated 66 realistic tasks across finance, file systems, and databases. Under baseline conditions, 12% of agent execution trajectories contain an exploitable TOCTOU gap. This is not a corner case: it is a structural property of agents executing tool calls across multiple steps.

Three Attack Surfaces That Did Not Exist Before Agentic Workflows

The first is external state injection. The agent reads state from an external source, stores the result in context, and acts on it later. An attacker who modifies the source between read and action causes the agent to act on stale data. The agent never re-validates; it trusts the cached result.

The second is sub-agent handoff poisoning. In multi-agent pipelines, an orchestrator validates preconditions then delegates execution to a sub-agent. The sub-agent receives the validated context, not the live state. Between orchestrator validation and sub-agent execution, the external world can change. The sub-agent executes against a precondition the orchestrator checked, not the current state.

The third is MCP server state swap. MCP servers maintain state across tool calls within a session. An attacker who modifies MCP server state between an agent's check call and its action call injects the gap at the protocol layer. Rashidi (arXiv:2607.05743): the MCP session model creates shared mutable state that any connected component can modify between agent calls.

Step Finance (2026): $40M in funds at risk from an agent acting on stale authorization state during a multi-step financial workflow. PocketOS (2025): a 30-hour service outage. An agent executed a resource deletion based on a precondition that was valid at check time but false at execution time.

Empirical Evidence: TOCTOU-Bench and the Incident Record

TOCTOU-Bench (arXiv:2508.17155) covers 66 tasks across three categories: finance (24 tasks), file systems (22), and databases (20). Each task involves an agent that checks a precondition and then takes an action. The evaluation metric is the fraction of execution trajectories that contain an exploitable TOCTOU gap.

Baseline: 12% of trajectories exploitable. After applying all three defenses simultaneously: 8%. A 33% reduction, not elimination. Tool-fusing, which redesigns tool servers to perform check-and-act atomically, achieves near-100% protection, but requires tool server redesign that no current framework ships.

NIST AI Agent Red-Teaming Guidance (CSA, 2026): 81% attack success rate against agents without temporal validation controls, versus 11% against agents with baseline defenses. The 70-percentage-point gap is the cost of treating agentic tool calls as stateless operations in a stateful world.

Replit (July 2025): an agent completed a privileged action before an authorization change took effect. It retained that authorization in subsequent calls. The authorization model assumed synchronous revocation; agentic caching made revocation asynchronous.

Current Frameworks Assume Atomicity They Do Not Provide

LangGraph, AutoGen, CrewAI, and LangChain model tool calls as atomic operations. None provide a mechanism to re-validate preconditions immediately before execution. None snapshot external state at check time to verify consistency at action time.

Rashidi (arXiv:2607.05743) evaluated four major frameworks against 193 security threat items. Policy failure rate: 69% to 98% across frameworks. 17.1% of agent actions in normal operation were out-of-scope relative to the declared task. Not because of attack: the frameworks do not enforce temporal consistency between precondition checks and actions.

Mansoor et al. (arXiv:2608.02645): frameworks assume tool calls are atomic and return consistent state. Reality includes delayed visibility, partial state, and ordering ambiguity. Writes propagate after the call returns, downstream effects lag, and concurrent calls from parallel agents return in non-deterministic order. Idempotency keys, standard in payment APIs since 2015, are absent from all major agent tool server specifications.

Nguyen et al. (arXiv:2603.09002): no framework covers more than half of any single security category across 193 threat items. TOCTOU is not a listed category: it falls between "input validation" and "state management," which means neither category covers it.

Three Defenses Ranked by the Gap They Actually Close

Prompt rewriting reduces the gap by roughly 15 to 20%. The agent is instructed to re-validate preconditions immediately before executing an action. This adds one tool call per action. The window narrows but does not close: the gap between re-validation and execution remains.

Monitoring with anomaly detection reduces the gap by roughly 25 to 30%. Agent tool calls are instrumented to flag state changes between check and action. If the monitored value changed between the agent's read and its write, the system alerts and aborts. This requires external monitoring infrastructure. It does not prevent the gap; it detects exploitation after the window opens.

Tool-fusing achieves near-100% protection for fused operations. The tool server exposes check-and-act as a single atomic operation, executed as a database transaction. The gap cannot be exploited if check and action are atomic.

MAGO Intel (intel.mago.team) instruments agent execution traces to detect TOCTOU patterns. It identifies state changes between check tool calls and action tool calls in the same execution trajectory, with timestamps sourced from MCP server logs.

None of the three defenses require framework changes. All can be applied to existing LangGraph, AutoGen, or CrewAI deployments. Tool-fusing requires tool server changes; the agent framework is not involved.

What Atomic Tool Execution Actually Requires From Infrastructure

Tool-as-transaction means the tool server, not the agent, owns the atomicity guarantee. The server accepts a check-and-act specification and executes both within a single database transaction or distributed lock. It returns the committed result or a conflict error. The agent receives one of two responses: success (action committed) or conflict (precondition failed at execution time).

Idempotency keys: the agent generates a unique key per intended action and passes it with every tool call. The server accepts the first call with a given key and returns a cached response for all subsequent calls with the same key. This prevents double-execution when the agent retries after a timeout during the check-to-action gap.

State snapshot tokens: the server returns a version token with each read operation. The agent includes this token with its write operation. The server rejects writes where the token does not match the current version, equivalent to optimistic locking. This pattern is standard in database APIs (etags, compare-and-swap) and absent from all major MCP server specifications.

Before deployment, enumerate every multi-step agent workflow where the agent reads state in one tool call and acts on it in a subsequent call. Each enumerated pair is a potential TOCTOU gap. Prioritize by value at risk (financial operations first), gap width, and attacker access to external state.

The check and the action are two different things. Until the tool server treats them as one, the gap is real. It is exploitable without kernel access, without race-condition timing, without elevated privileges. Enumerate the read-then-write tool pairs in your pipeline before someone else does.

Top comments (0)