Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

AI agents recover reliably when an error response tells them three things separately: what failed, what data is trustworthy, and what action is safe next. An HTTP status or opaque code alone is rarely enough. Design errors as a contract for software and a concise explanation for people, using stable machine fields, structured validation details, explicit retry guidance, and sanitized diagnostics.

Start with a contract, not an exception dump

An agent should not have to infer an error category from prose. Return the transport-level result your protocol defines, then add a stable application identity. For HTTP APIs, RFC 9457 (published by the IETF in July 2023 and obsoleting RFC 7807) provides the standard Problem Details shape, commonly sent as application/problem+json.

  • Transport result: the real HTTP status, or the protocol’s execution-error flag.
  • Stable identity: a problem type URI or versioned error code that clients can switch on.
  • Human context: a short, occurrence-specific detail sentence.
  • Structured extensions: typed fields an agent can process without parsing prose.
  • Occurrence reference: an identifier support staff can find in protected logs.

RFC 9457’s standard members are type, title, status, detail, and instance. The standard permits problem-specific extensions, but it does not prescribe your domain’s error vocabulary. Use established protocol conventions rather than inventing a second generic envelope.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Separate stable data from explanatory text

Keep every value that software must act on in a typed field. Treat detail as display text, not a hidden data format. RFC 9457 explicitly says consumers should not parse the detail prose; its purpose is to help correct the problem, not to expose debugging information.

Validation example

{
  "type": "https://api.example.test/problems/invalid-date-range",
  "title": "Invalid date range",
  "status": 422,
  "detail": "The end date must be later than the start date.",
  "errors": [
    {
      "pointer": "#/end_date",
      "code": "must_follow_start_date",
      "expected": "A date later than start_date"
    }
  ],
  "retryable": false
}

The errors, pointer, code, expected, and retryable members in this example are application choices, not RFC 9457 standard members. A JSON Pointer identifies the offending field precisely, allowing an agent to correct only the invalid argument.

Use names agents can distinguish

Choose distinct tool and error names. “Request failed” does not tell an agent whether to edit an argument, authenticate, wait, call another tool, or ask a person. Prefer identities such as invalid_date_range, missing_scope, rate_limited, and upstream_unavailable. Keep them stable when wording, localization, or implementation changes.

Tell the agent what recovery is possible

Every failure should map to a recovery class. Do not encourage blind retries.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Recovery class Include Typical agent action
Correct input Field pointer, violated constraint, acceptable values Rewrite arguments and call again once
Retry later Explicit retryability and a server-supported delay Wait, then retry within policy
Prerequisite Required state or operation that must happen first Complete the prerequisite or use the named tool
Permission Missing capability and safe request path Ask for authorization or explain the limit
Human decision Why automation cannot proceed and available choices Ask the user a focused question

Use a boolean such as retryable only if its meaning is precise. For throttling or temporary unavailability, return a delay that your service can honor and use the HTTP Retry-After header where appropriate. A validation failure, denied permission, or permanent capability limit should not advertise retryability.

Make tool execution errors visible to models

The Model Context Protocol (MCP) tools specification, currently a draft, distinguishes protocol errors—such as an unknown tool or malformed request—from execution errors such as an API failure, validation problem, or business-rule rejection. The draft says clients should provide execution errors to models so they can self-correct. Verify the stable MCP release before treating draft wording as a production norm.

Preserve that distinction in your adapter. A malformed MCP request is not repaired by changing a business argument; an execution error may be. Return the original tool name, stable category, structured fields, and concise recovery guidance so the model has enough context without receiving a stack trace.

Design the human-facing layer separately

The same event can need two presentations. An agent needs field paths and machine-stable categories; a person needs an honest status, completed work, and a short set of choices.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • State what the agent did and what it could not do.
  • Preserve or report successful partial work, including identifiers for created items.
  • Offer two or three concrete next steps: retry, change a value, grant access, or escalate.
  • Explain permission limits directly rather than implying a transient outage.
  • Say whether the limitation is permanent or temporary.

Do not claim a whole operation failed when an earlier step succeeded. Partial results should have their own structured status so an agent does not repeat side effects.

Sanitize diagnostics without hiding recovery information

Return interface-level facts, not implementation internals. Stack traces, internal hostnames, SQL fragments, credentials, tokens, exception class names, and infrastructure topology belong in access-controlled logs. AWS guidance for agentic systems likewise recommends validating agent-produced inputs, enforcing schemas in the invocation path, applying resource and output limits, and returning structured, sanitized error categories.

An opaque correlation or occurrence identifier can connect a response to server logs, but it is not a substitute for an actionable error. Rotate or scope identifiers appropriately, and ensure they cannot reveal sensitive sequencing or tenant information.

Validate agent inputs at the boundary

  1. Validate syntax and schema first. Reject unknown fields, wrong types, oversized values, and invalid encodings before business logic runs.
  2. Validate semantic constraints. Check relationships such as date ordering, ownership, state transitions, and allowed combinations.
  3. Bound resource use. Set limits for request size, execution time, pagination, tool output, and fan-out.
  4. Return all safe field errors together. This avoids a sequence of one-error-at-a-time calls, while omitting fields whose values would expose secrets.
  5. Log the protected diagnostic. Attach the occurrence identifier and relevant server-side context without echoing it into the model unless needed.

Measure the contract with the agents you actually use

There is no established universal recovery-rate percentage for agent error schemas. Anthropic’s tool-design guidance stresses that tool names, response formats, and returned context affect tool-use evaluation and can vary by model. Test your own combinations rather than assuming one wording works everywhere.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Useful evaluation cases

  • One invalid field with an obvious correction.
  • Several invalid fields in one request.
  • A valid request blocked by a missing permission.
  • A timeout after a side effect may have completed.
  • A rate limit with and without a server-provided delay.
  • A malformed tool call versus a valid tool call whose business operation failed.
  • Unexpected or malicious values designed to trigger verbose exceptions.

Record whether the agent selected the right recovery class, preserved completed work, avoided duplicate side effects, and asked a human only when necessary. Evaluate response size and latency as well as task outcome; excessive context can crowd out the information needed for the next call.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failure modes and fixes

The agent retries a permanent error

Cause: every failure is presented as a generic server error. Fix: provide a stable category, explicit retryable: false, and the field or permission change required.

The agent edits the wrong field

Cause: the constraint exists only in a sentence. Fix: return a JSON Pointer and a machine-readable constraint code for each invalid field.

A parser breaks after copy changes

Cause: client code extracts values from detail. Fix: move data into typed extensions and treat prose as non-contractual.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Useful errors leak secrets

Cause: raw exceptions or upstream responses are passed through. Fix: map internal exceptions to sanitized categories and keep full diagnostics in protected logs.

The agent repeats a completed action

Cause: a timeout is reported without side-effect status. Fix: return an operation identifier and an explicit state such as completed, unknown, or not_started, with an idempotent status-check operation.

Humans cannot tell what to do

Cause: the UI displays a code or raw JSON. Fix: render the concise detail, completed work, and two or three safe next actions while retaining the structured payload for the agent.

Testing agent workflows with visual evidence

When an agent operates a web interface, screenshots can reveal whether an error banner, disabled control, or permission notice actually appeared. ScreenshotNeo is a website screenshot API and MCP server; its clean capture removes known cookie banners, newsletter popups, and chat widgets before capture, while bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP tools include take_screenshot, get_page_info, and capture_pdf, so an AI client can inspect the resulting state. Use it as an observation aid, not as a replacement for the structured error contract.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

Call ScreenshotNeo with one request when you need a clean visual of a page involved in an agent workflow. The API accepts PNG, JPEG, WebP, or PDF output; its options include full-page capture, CSS-selector elements, waits, custom headers and cookies, hiding selectors, and signed asynchronous jobs. Only clean shots are billed, and each response identifies the page verdict and billing result in headers.

See the ScreenshotNeo documentation for the complete parameter list.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, popups, and chat widgets are removed before the shot. Bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

FAQ

Should every error use HTTP 4xx or 5xx?

Use the status that accurately represents the transport result, then add your stable application identity and structured details. Do not overload one status to encode every business case.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can an agent read the RFC 9457 detail field?

It may display or summarize it, but clients should not parse it for machine decisions. Put actionable data in extensions.

Should error responses include stack traces in development?

Keep traces in protected logs even during normal operation. A controlled developer-only environment can expose additional diagnostics, but do not let environment switching accidentally disclose them to production agents.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.