Incident response for an agent that took a wrong real-world action: containment with a kill switch, data repair from the audit log, diagnosing from traces (ambiguous tool results, missing validation, prompt injection, model change), and the guardrails added afterwards.
First contain: switch the write tool or the whole agent off with a feature flag, while read-only help can stay up. Then repair: use the audit log of tool calls to find every affected change, reverse it and tell affected customers; if personal data reached the wrong person, assess it under the Notifiable Data Breaches scheme. Then diagnose from the traces: the exact tool results the model saw, the arguments it produced, the model and prompt version. Typical causes are an ambiguous tool result (it chose by name), missing server-side validation (the tool trusted the argument), prompt injection in retrieved content, or a model or prompt change. The fix is server-side guardrails: ownership checks, typed ids, amount limits, idempotency and approval for money movements, plus the conversation as a regression case. The lesson: the model will be wrong sometimes, so the tool must be safe when it is.
"I'd treat it like any production incident where data was changed incorrectly, with one extra question: what did the model see that made this look right? Step one is containment. Our agent tools sat behind feature flags, so I'd turn off
apply_creditimmediately, leaving read-only tools available. Step two is scope: every tool call is audited with the user, the conversation id, the arguments and the result, so I can query exactly which credits the agent applied since the last good release and which went to the wrong account. We reverse those, tell the affected customers and, if one customer could see another's details, the privacy officer assesses it under the Notifiable Data Breaches scheme.For example, at [company] we had [an agent that applied goodwill credits]. The trace showed the model called
find_customerwith a name, got back [three] matches, and passed the first id toapply_credit. The tool accepted any customer id and any amount up to [$500]. So the root cause wasn't really 'the model hallucinated'; it was that our tool allowed an action that the agent's own user wasn't scoped to and gave the model an ambiguous result. We fixed it by makingapply_creditrequire the id of the customer in the current case, rejecting ambiguity infind_customer, turning credits into proposals approved by the agent's human operator, and adding the conversation to our evaluation set. Wrong credits went to [zero] over the next [quarter].The mistake I see is fixing this with a stronger system prompt. Prompts lower the rate of mistakes; they don't make the tool safe. The tool must refuse anything the user couldn't do by hand."
| Phase | Actions | Owner |
|---|---|---|
| Detect | Alert, ticket or anomaly in agent write metrics | On-call |
| Contain (minutes) | Feature flag off for the write tool; keep reads if safe | On-call engineer |
| Scope (hours) | Query audit log of tool calls; list affected records | Engineer + data owner |
| Repair | Reverse changes, notify customers, NDB assessment if needed | Product, support, privacy officer |
| Diagnose | Replay traces; classify root cause | Engineering |
| Prevent | Guardrails, eval cases, monitoring, ADR | Team; reviewed in post-incident review |
| Root cause | Evidence in traces | Fix |
|---|---|---|
| Ambiguous tool result | Several matches returned; model picked one | Return an error asking for disambiguation; use ids from context |
| Tool trusts arguments | Write succeeded for an account outside the case | Ownership and scope checks in the handler |
| Prompt injection | Retrieved note or email containing instructions | Treat tool output as data; approval for writes; Prompt Shields |
| Model or prompt change | Started after a deployment or model version update | Pin model versions; evaluation gate on changes |
| Retry duplicates | Same call id executed twice | Idempotency keys on writes |
After the fix, [4%] of credit proposals were rejected by operators in the first month, each one a case the old design would have applied automatically; at an average of [$120] per wrong credit that was about [$…] a month of avoided write-offs, and the rejection rate became a tracked quality metric.
Checks whether the candidate handles an agent incident with real incident discipline and fixes the system design rather than the prompt.
Green flags
Red flags
The model chooses arguments from what is in its context. If the context contains several plausible values, missing values, or text that looks like an instruction, it will sometimes choose wrongly, and confidently. Nothing in the loop checks the choice unless you add it.
user: "give Sam Lee a $50 credit for the late delivery"
│
├─ find_customer("Sam Lee") → [C-102 Sam Lee (NSW), C-877 Sam Lee (VIC), C-940 Samantha Lee]
│ ↑ ambiguous result handed to the model
└─ apply_credit(customerId="C-102", amount=50)
↑ no check that C-102 is the customer in this support case
Replay the run in an evaluation harness with the same model version and tool results (mock tools return the recorded results). Run it many times: if the model picks the wrong id 30% of the time, the design is the problem, not a one-off. Change one thing at a time (tool result shape, validation, prompt) and measure.
If one customer's data was shown to another, or changed in a way that reveals it, the Privacy Act's Notifiable Data Breaches scheme requires an assessment within 30 days and notification to the OAIC and affected individuals if serious harm is likely. Record the assessment even if not notifiable.
Blameless: the model, the prompt and the tool design are system parts. Actions should be specific and owned: server-side checks, evaluation cases, metric and alert, autonomy level review, and an ADR stating the rule for agent write tools.
find_customer that returns three matches and run an agent 50 times; count how often it picks the wrong one.apply_credit only accepts the case's customer id and write xUnit tests for refusal.Before: a write tool that trusts the model. After: scoped, validated, idempotent and approval-based.
// BEFORE: any customer, any amount up to $500, executes immediately
[Description("Applies a credit to a customer account.")]
public Task<string> ApplyCredit(string customerId, decimal amount, string reason, CancellationToken ct) =>
credits.ApplyAsync(customerId, amount, reason, ct).ContinueWith(_ => "Done", ct);
using System.ComponentModel;
namespace Support.Agent;
public sealed record CaseContext(Guid CaseId, string CustomerId, string OperatorId);
public sealed class CreditTools(CaseContext ctx, ICreditService credits, IProposalStore proposals, ILogger<CreditTools> audit)
{
[Description("Finds a customer by exact customer id or email. Returns an error if the match is not unique.")]
public async Task<string> FindCustomer(string idOrEmail, CancellationToken ct)
{
var matches = await credits.FindCustomersAsync(idOrEmail, ct);
return matches.Count switch
{
0 => "No customer found.",
1 => $"Customer {matches[0].Id}: {matches[0].DisplayName}",
_ => "More than one customer matches. Ask the operator which customer id to use." // never let the model pick
};
}
[Description("Proposes a goodwill credit for the customer on the current case. The operator must approve it.")]
public async Task<string> ProposeCredit(string customerId, decimal amount, string reason, CancellationToken ct)
{
// Scope: the agent may only act on the customer bound to this case.
if (!string.Equals(customerId, ctx.CustomerId, StringComparison.Ordinal))
return $"Refused: credits can only be proposed for the customer on case {ctx.CaseId}.";
if (amount is <= 0 or > 200m)
return "Refused: amount must be between $0.01 and $200.";
var key = $"{ctx.CaseId}:{customerId}:{amount}"; // idempotency: duplicate calls make one proposal
var proposalId = await proposals.UpsertAsync(key, new CreditProposal(ctx.CaseId, customerId, amount, reason), ct);
audit.LogInformation("Agent proposed credit {ProposalId} case {CaseId} customer {CustomerId} amount {Amount} operator {OperatorId}",
proposalId, ctx.CaseId, customerId, amount, ctx.OperatorId);
return $"Proposal {proposalId} created for {amount:C}. The operator will approve or reject it.";
}
}
This incident is the agent version of 'never trust client input'. The model is a client that is usually right and occasionally confidently wrong, so the safety of the system has to live in the tool contract and the approval design, not in the model. I also push for an autonomy review after the fix: some write tools may never need to be autonomous because the human approval costs seconds and the error costs real money and trust.
| Guardrail | When it fits | Cost | When not to |
|---|---|---|---|
| Scope binding to case/customer | Any agent acting within a case or session | Small: pass context to tools | Genuinely cross-account admin tasks (use approval) |
| Human approval of proposals | Money, external messages, deletes | Operator time per action | High-volume, reversible, low-value changes |
| Hard limits and rate caps | All write tools | Occasional legitimate refusal | Never skip; tune the numbers |
| Idempotency keys | Any write that may be retried | Key storage | Pure reads |
I'd measure success by wrong-write rate (reversals of agent actions), proposal rejection rate and time to contain in game-day drills.
With tool calling, you describe functions (name, description, JSON schema of parameters) in the request. The model can reply with a tool-call request instead of text; your app executes it and sends the result back, and the model continues. In Microsoft.Extensions.AI, AIFunctionFactory.Create turns a C# method into a tool, you pass it in ChatOptions.Tools, and UseFunctionInvocation() runs the loop.
The model chooses the arguments, so treat them as untrusted input: validate them, authorise against the signed-in user inside the tool, expose only least-privilege tools, require approval for side effects and cap iterations. The trade-off: tools make the model useful, but every tool widens what a confused or manipulated model can do.
Prompt injection is text that makes the model follow an attacker's instructions instead of yours. Direct injection is the user typing "ignore your instructions". Indirect injection hides in content the model reads: a retrieved document, an email, a web page or a tool result. LLMs have no hard boundary between instructions and data, so you can't prompt your way out of it.
Defend in layers, assuming the model can be manipulated: least-privilege tools, authorisation in code from the signed-in user, delimiting untrusted content, Prompt Shields detection, treating output as untrusted (encode it, block exfiltration links, validate before acting), and human confirmation for side effects. Test it with a red-team set in CI. The trade-off: every capability you give the model is something an attacker can borrow.
You can't unit-test an LLM into correctness, so you measure it. Build a golden set of real cases with expected sources or reference answers, including out-of-scope and adversarial ones. Measure retrieval (recall@k) separately from answers (groundedness, relevance, completeness). Run deterministic checks first (valid JSON, valid citations, refusals), then LLM-as-judge evaluators such as those in Microsoft.Extensions.AI.Evaluation, calibrated against human grades.
Treat prompts, model versions and retrieval settings as code: every change runs the suite in CI against thresholds. In production, track feedback and add new failures to the set. The trade-off: a bigger, richer evaluation set catches more regressions but costs more tokens and expert time to build and run.
How to tell it (STAR)
**S:** We had a support agent applying goodwill credits directly for [150] operators, and finance found credits that didn't match any case. **T:** I was incident lead: stop it, fix the data and make sure it couldn't recur. **A:** I turned off the credit tool with its feature flag within [15 minutes], then used the tool-call audit log to find [23] wrong credits in [10 days] and reversed them with support contacting customers. The traces showed `find_customer` returning several people with the same name and the model taking the first; the credit tool accepted any customer. We redesigned it as scoped, capped, idempotent proposals approved by the operator, made ambiguous lookups an error, and added those conversations to the CI evaluation set. **R:** Wrong credits went to [zero] over the next [quarter], and operators rejected [4%] of proposals, each one a mistake that would previously have gone straight through.
Last updated 23 Nov 2026.