Error Contracts Between Agents and External APIs
Formal contracts define what agents must preserve at API boundaries—and enforce them at runtime.

Error contracts between agents and external APIs define what must hold before a call, what must remain true through a workflow, and how failure must be repaired. Their central purpose is to turn assumptions about agent behavior into enforceable rules. For agent systems to be reliable, these rules must hold at every boundary where actions, artifacts, or recovery knowledge pass from one system to another.
Why agents break at API boundaries in ways deterministic software does not
APIs expect deterministic callers that honor explicit contracts, while agents act on prompts and natural language instructions. That mismatch becomes concrete when a workflow requires an agent to relay a signed URL byte-for-byte, consume a token before expiry, or return an OAuth state parameter unchanged. Understanding the task does not guarantee any of these behaviors. ContractBench found that models good at general tool use could still fail at observation contract compliance, and that larger or newer models did not always do better. Its leading model reached 77.8%.
The problem also extends beyond individual calls. Bhardwaj's ABC paper points to the gap between formal software contracts and informal agent instructions as a root cause of behavioral drift and silent degradation. A financial agent can exceed its trading authority through a sequence of individually plausible steps without any single API call flagging the error. Boundary checks therefore have to cover both local correctness and behavior over time.
What an error contract actually is, and what it is not
An error contract is a formal, runtime-enforceable agreement that specifies preconditions, invariants, governance policies, and recovery mechanisms. For an OAuth token, that means defining whether it is valid before use, which authorization scope must remain intact, and what happens if a check fails. For a signed URL, it also means defining how the artifact must survive its passage between steps.
Bhardwaj's Agent Behavioral Contracts v1 expresses this structure as C = (P, I, G, R). ABC v2 separates hard and soft invariants and governance policies in C = (P, I_hard, I_soft, G_hard, G_soft, R). Hard constraints must never be violated, while soft constraints allow transient violations within a bounded recovery window. Its (p, δ, k)-satisfaction notion accounts for LLM non-determinism.
Output guardrails filter or redirect responses and need additional rules to define preconditions and monitor invariants across a workflow. HTTP status handling, retry logic, and instructions to be careful with tokens also need rules that the system can enforce.
The four categories of failure agents actually encounter at API boundaries
The first category is runtime protocol errors, including rate limiting, authentication failures, service errors, and missing resources. TRAIL identifies these familiar API tool errors through responses such as HTTP 429, 401, 403, 500, and 404. They are visible failures, but their visibility can distract engineers from failures that return no useful signal.
The second category is observation contract violations. An agent can choose the right API yet break the workflow by using an expired signed URL, truncating it, re-encoding reserved characters, or reordering signed parameters. The initial request can succeed while a downstream system rejects the relayed artifact. ContractBench also finds that agentic post-training can erode compliance, so a newer model is not automatically safer here.
The third category is tool definition and environment failures, including misleading tool definitions, missing API keys, incorrect file permissions, and misconfigured environment variables. TRAIL distinguishes these setup problems from explicit HTTP errors because they disrupt the agent's reasoning path. The fourth category is tool return failures in chained calls. If a function lacks a return value or has an implementation defect, the agent may halt or continue reasoning without a result.
How API error responses need to be redesigned to serve agents, not humans
A plain-English diagnosis leaves the agent to infer a repair. That inference costs tokens and can produce the wrong correction. Engineers who build APIs for agents should put machine-readable recovery information in the response itself.
Canedo and Chethan's June 2026 Self-Reflective API pattern supplies a recovery_feedback.suggestions[] payload on validation errors. Instead of only describing the problem, it tells the agent what to change before retrying. Their study found that Anthropic models completed far more tasks, with roughly double the per-success token efficiency. The benefit was not significant for gpt-4o-mini, which makes testing against the actual runtime important. A second billing API domain also reproduced the pattern.
This is the server-side half of the contract. Just as Cache-Control and ETag let HTTP clients manage caching without trial and error, structured recovery suggestions let agents repair requests without deriving the answer again. The repair guidance belongs with the failure payload.
Enforcing contracts at runtime: preconditions, invariants, and recovery mechanisms as code
The agent-side half starts by turning the specification into checks that run during execution. Preconditions test token validity, authorization scope, and rate-limit headroom before an action. Invariants check what must stay true, and governance policies set out when the agent must refuse or escalate a decision. Recovery mechanisms then define structured retry, rollback, or a human checkpoint when a constraint fails.
Bhardwaj's Stochastic Drift Bound Theorem states, in plain terms, that recovery must be faster than the system's tendency to drift. Formally, a recovery rate γ greater than the natural drift rate α bounds drift to D* = α/γ in expectation. This is a conditional bound.
The ABC work reports 88–100% hard constraint compliance across contracted models, with full recovery for frontier models, at under 10ms overhead per action. That overhead addresses the practical objection that runtime checking is too expensive. ContractSpec provides a configuration-based interface with expression-based predicates and hard/soft separation. Engineers must still make that separation explicitly, since treating latency preferences like authorization limits creates needless interruptions, while treating authorization limits like preferences permits serious failures.
Observation contracts: the inter-step integrity problem that behavioral contracts alone do not solve
Behavioral contracts govern what an agent does over time. Observation contracts set out what it must keep intact in the artifacts it receives between steps. A presigned S3 URL makes the distinction clear. Its later use depends on both its expiry window and its exact bytes, so correct task planning alone cannot establish that it remains usable.
ContractBench isolates these obligations through separate validity and integrity tests. It uses a virtual clock for temporal constraints and cryptographic hashes for byte integrity, with failure labels drawn from real-world API specifications. Its findings locate the difficulty in mid-trajectory restraint. The agent has to know when not to transform what it receives.
Validity failures require expiry metadata and refresh before use. Integrity failures require treating the URL as an opaque blob that must be relayed verbatim. A fresh copy of an expired artifact can still be corrupted. Preserving bytes, in turn, does not extend its lifetime.
When errors cross session boundaries: cache invalidation for agent memory
HTTP cache invalidation is a useful model for keeping recovery knowledge from one session to the next. When server-side data changes, an invalidation contract needs to identify stale suggestions without discarding valid ones. Wu and Canedo's Invalidation Contracts for Cross-Episode Agent Memory attaches version stamps and cacheability hints to recovery suggestions for this purpose.
Their study separates validity from compliance. Validity measures whether the cached suggestion is still correct and depends on the protocol. Compliance measures whether the model applies a valid suggestion on the first attempt. Claude Haiku 4.5 achieved full first-try compliance, while Claude Sonnet 5 fell to 11% or below because it refused fixes that added fields missing from the original request.
Granularity makes this more than a routine eviction problem. With Row-level invalidation, compliance rose by 55.6 to 66.7 percentage points in three of the seven models tested. Table-level invalidation discarded co-located valid entries and dropped post-drift first-try rates to 0% on five of seven models. Its loss of token savings shows why imprecise invalidation can actively undermine the reason for caching.
State persistence and error recovery across agent restarts
Cross-session memory does not answer the separate question of where a crashed agent should resume. If execution state is not saved, a restart can repeat side-effecting API calls that have already succeeded.
The 2026-07-28 Model Context Protocol specification introduced a stateless protocol core in which requests carry enough information to be handled independently. That places session persistence outside the protocol guarantee. It defines a responsibility boundary for MCP. As tasks become longer-running, the application and runtime must carry the state that independent tool calls do not preserve.
Each checkpoint needs the successful API calls and their side effects, the violated constraint and attempted recovery, the validity of cached suggestions, and the expiry windows of artifacts in flight. A purpose-built agent runtime should have checkpoint management and error-aware restart built in, so save-state logic does not have to be scattered through application code.
Multi-agent pipelines and the compositional failure problem
A pipeline turns one agent's output into another agent's assumption. If a corrupted artifact crosses that handoff without a precondition check, the downstream agent processes it as valid. Each node's input preconditions should therefore derive from the previous node's output postconditions.
The ABC framework establishes sufficient conditions for safe contract composition and derives probabilistic degradation bounds as chains lengthen. ContractSpec supports file-reference composition so a pipeline contract can combine individual agent contracts without restating every constraint. This matters because local compliance alone does not establish compliance across the chain.
Resource bounds remain a separate obligation. A behaviorally compliant pipeline can still exhaust rate limits, while a pipeline within quota can still produce incorrect outputs. Missing tool returns also need pipeline-level handling because downstream agents may receive no signal when a chained function fails to return. Composition must set out what happens at that boundary when an upstream action fails to produce a usable result.
The liability and governance gap that missing error contracts create
The same missing boundaries create an accountability problem when an agent makes an incorrect supplier payment, misprices a product, or deletes data. Without a formal error contract, the organization lacks an artifact showing how behavior was specified, monitored, and governed.
Clifford Chance's February 2026 analysis describes technology agreements written for passive, predictable software under human control. Supplier disclaimers can leave customers responsible for agent actions even when they configured the agent correctly. Exclusions for consequential or indirect losses can cover lost profits, regulatory fines, and data loss, while liability caps may be tied to subscription fees. These terms can leave a substantial gap between the harm and the available remedy.
Clifford Chance also identifies the need for contractual rights around oversight, transparency, and explainability. If customers cannot see the logs or reasoning behind a decision, they may struggle to provide the audit trail needed when it is challenged under GDPR and the EU AI Act. Runtime error contracts cannot replace those legal rights, but they provide a technical basis for demonstrating control at the API boundary.
A first-principles framework for designing error contracts at the agent-API boundary
First, classify each interaction before specifying its recovery. Signed URLs and OAuth tokens need relay and expiry rules, chained tool calls need rules for missing returns, and downstream consumers need compositional contracts. Cached recovery suggestions need an invalidation contract, with row-level granularity as the safe default. This assigns each failure to the layer capable of handling it.
Second, make API validation responses carry recovery_feedback.suggestions[], with version stamps and cacheability hints on every suggestion. Third, implement the agent-side obligations as runtime checks. Check preconditions before calls, monitor invariants as execution proceeds, and decide which constraints are hard and which allow bounded recovery.
Fourth, specify checkpoint contents as part of the contract. Persist successful calls and side effects, error state and recovery attempts, cached-suggestion validity, and artifact expiry windows. Fifth, use the output postconditions of the node before each pipeline node to work out its input preconditions, and set out what happens when a node returns nothing.
These decisions also define the infrastructure requirement. A purpose-built agent runtime should handle persistence, checkpoints, and pipeline error propagation so engineers can focus on the contract itself. The goal is not to make an agent promise greater care, but to make safe continuation a condition the system can enforce.
Sources
- Invalidation Contracts for Cross-Episode Agent Memory
- ContractBench: Can LLM Agents Preserve Observation Contracts?
- Agent Behavioral Contracts: Formal Specification andRuntime Enforcement for Reliable Autonomous AI Agents
- TRAIL: Trace Reasoning and Agentic Issue Localization
- Agentic AI: The liability gap your contracts may not cover


