An HTTP 200 response does not prove an AI tool completed its task. Before reporting success, check the response structure, apply business rules and confirm any change in the source system.
AI tool output validation needs four checks:
- Schema: Are required fields present, correctly typed and complete?
- Business rules: Do values, permissions, scope and data age meet the request?
- Post-action state: Did the intended change happen? A £75.00 refund needs a matching payment record - not just a success message.
- Failure and recovery: Should the system stop, retry or seek review? An unresolved write is unknown, not failed.
Enforce these checks in code, keep a redacted audit record and set retry limits. If a write’s outcome is unknown, resolve it before retrying to avoid duplicate actions.
::: @figure
{AI Tool Output Validation: Four Checks Before Success}
:::
AI Security Lesson 75: AI Tool Output Validation Explained for Teams
Check Tool Inputs and Outputs Against a Schema
Validate arguments before a tool runs, then validate its response before anything downstream uses it. Enforce the contract at the tool boundary. Reject malformed JSON, wrong types, unsupported values and unexpected fields. Use additionalProperties: false for strict contracts.[6] Do not coerce types or treat API errors as empty results.
Schema checks decide whether an output is fit for interpretation. Business rules decide whether it is fit for use.
Check Required Fields and Completeness
In JSON Schema, properties defines fields; required makes them mandatory.[7][8] Check identifiers, permitted values, formats, units and nullability at every relevant nesting level. A required field can still be empty, so enforce string length separately. Allow null only where the contract permits it.
Use ISO 8601 timestamps with time zones and explicit currency codes such as GBP. Keep £1,250.00 for display only.
Require status, error indicators, timestamps, source IDs, result counts and pagination metadata where needed. Compare page counts with returned items - not dataset totals. Check missing records, missing continuation tokens and contradictory completion flags further.
A structurally valid response can still be incomplete or contradictory. Send ambiguous results for business-rule checks or verification against an authoritative source. Do not fill the gaps yourself.
Return Field-Level Schema Errors
Return a machine-readable error containing the field path, error code, expected constraint, received type or value class, severity and next action. These errors should stop silent failures from being treated as success.
Keep input repair separate from output repair: the agent may correct known arguments, but it must not invent missing response values.
| Schema failure | Typical signal | Safe handling | Retry suitability |
|---|---|---|---|
| Malformed JSON | Invalid token or unexpected end of input | Reject; retain a protected original | Bounded retry only for idempotent reads |
| Missing fields | Required path absent or disallowed null
|
Identify missing paths | Only if the producer can supply the missing data |
| Invalid types | String instead of number; object instead of array | Report expected and received types; do not coerce | Only after input or producer correction |
| Partial payloads | Incomplete nested records or inconsistent pagination | Mark incomplete; do not pass it downstream as success | Continue only with confirmed continuation state and safe retry behaviour |
Store an immutable original response separately for audit and replay. Apply access controls, encryption and retention limits. In redacted logs, record tool and schema versions, request ID, validation timestamp, source, field-level errors and retry decision. Never expose credentials or unnecessary personal data in diagnostic messages.
Only responses that pass schema validation move to business-rule checks.
Check Results Against Business Rules
A response can pass schema validation and still fail business checks. Keep business rules outside the model’s control: enforce them through deterministic checks in the executing service. Compare returned values with the approved request and authoritative records - not the model’s success message.[12] This catches responses that look successful but contain incorrect values or outcomes.
Check Values, Scope and Data Age
Match order, payment, customer and tenant IDs against the authenticated context and source data.[9][14] Check quantities, prices, discounts, VAT and totals. Enforce amount limits, currency, eligibility dates and stock availability. Set record-age limits for each decision and reject stale records before proceeding.[13][15] These checks catch outputs with the wrong tenant, outdated data or mismatched amounts.
Hypothetical UK retailer refund: A customer requests a £75.00 refund from order
UK-10482. Before execution, verify ownership, refund eligibility, GBP currency and a current refundable balance of at least £75.00. Afterwards, match the returned order and payment references to the payment record, confirm exactly £75.00 in GBP and check that total refunds do not exceed the captured amount. A response reportingsucceededin USD fails business validation; do not treat it as a successful refund.[16]
Once the values pass, check whether the actor has permission to perform the action.
Enforce Permissions and Prevent Duplicates
Check permission for the exact object, action and state, not just the actor’s role. Verify approvals against an authoritative record that covers the actor, exact operation and validity period. Never trust an agent-supplied user_confirmed value.
Enforce balance and stock constraints atomically so concurrent requests cannot bypass them. Reuse an idempotency key only for the same intended operation and parameters.[1][10][11] These checks prevent a valid-looking response from hiding an action performed without permission or a repeated action.
| Rule | Input | Validation condition | Failure classification | Permitted response |
|---|---|---|---|---|
| Required refund amount | User request | Present, numeric and greater than £0.00 | Missing or invalid input | Request the amount again; do not call the tool |
| Currency match | Request and payment record | Requested and payment currencies match; GBP in this example | Business constraint | Reject; require explicit currency handling |
| Refundable balance | Request and payment record | Amount does not exceed current refundable balance | Business constraint | Block; disclose the limit only if permitted |
| Tenant and customer scope | Authenticated context and order | Order belongs to the requesting customer and tenant | Permission violation | Deny without exposing cross-tenant details |
| Refund approval | Approval service and request | Valid approval covers the amount and operation | Permission or workflow violation | Block; route for approval |
| Duplicate request | Idempotency store and provider record | No completed refund exists for the operation key | Business constraint or duplicate | Return the safely matched outcome; otherwise investigate |
| Stock availability | Inventory record | Sufficient stock at commit time | Business constraint | Reject or offer an alternative |
| Freshness | Source timestamp | Record age is within the permitted limit | Repairable stale data or safety block | Refresh; block if freshness remains unverified |
When a check fails, classify the outcome as business_validation_failed, retain the raw response and findings, and stop downstream use. If side effects are possible, verify the authoritative system before retrying.[10]
Verify the State After an Action
Once schema and business checks pass, confirm that the source system actually changed. This is the final check against silent failures.
Define the required postcondition before execution. Creation requires a new authoritative record with the expected type, owner, tenant, status and values. An update requires the requested change and a newer version or timestamp. Deletion requires confirmed absence or a retention-policy deletion marker - not just a failed lookup. A transaction requires a source record confirming the amount, currency, account and status.[20][21]
Keep acceptance, completion and delivery separate. A queued message has been accepted for processing; it has not yet been delivered. Check sending and downstream delivery against their own status records. Report ‘delivered’ only when delivery evidence exists.[21][22]
Re-read the Authoritative Record
Save the tool response, then query the source system - not a cached response or an echoed request. Compare identifiers, tenant, quantities, totals, currency, requested fields and status transitions against the postcondition. Check the version and timestamps against the pre-action snapshot. Where supported, require an operation or correlation identifier that links the change to this action. A later timestamp alone does not prove your update took effect.[20][21]
Resolve Unknown Outcomes Before Retrying
Classify verification as confirmed, failed or unknown. For eventually consistent updates, use bounded polling with increasing delays and a fixed deadline, or use the provider’s wait mechanism. Stop when completion or failure is confirmed. An expired deadline means unknown, not failed: the write may have succeeded before the read path caught up.[19][23]
If verification leaves the outcome unresolved, check it before retrying. Consult the operation-status endpoint, authoritative record or event history. Reuse the original idempotency key with unchanged parameters only within the provider’s documented guarantees. Stripe’s API v1 retains keys for at least 24 hours. After the retention window, do not assume the key still prevents duplicates. If the outcome remains uncertain, pause dependent actions and escalate.[17][18]
Classify Failures and Choose Safe Recovery
After schema, business and post-action checks, classify the failure before choosing how to recover. Record the validation finding, authoritative state, possible side effects, idempotency protection and retry count. Use the evidence - not the tool’s success flag - to classify the failure.
Match Failure Types to Recovery Actions
| Failure class | Evidence | Safe recovery |
|---|---|---|
| Schema | Missing required field, wrong type or invalid enum | Return field-level errors. Repair arguments only if they caused the fault; otherwise fix the adapter or integration. |
| Business rule | Amount exceeds a limit or record is closed | Stop and report the violated rule. Do not retry unchanged. |
| Permission | Denied capability, HTTP 401/403 or tenant mismatch | Stop; use an authorised workflow or escalate. |
| Transient | Rate limit or temporary service fault, with no unresolved write | Retry within attempt and time limits; honour the supplied retry interval. |
| Dependency | Downstream outage or unusable prerequisite result | Retry only if recovery is plausible and repetition is safe; otherwise queue or escalate. |
| Semantic | Structurally valid but stale, incomplete or wrong content | Fetch updated data, reconcile or request human review. |
| Unknown outcome | Unresolved write state | Resolve state before any retry. |
These classes guide whether to retry, stop, escalate or check the state again.
Enforce retry limits in code. Honour Retry-After and use exponential back-off with jitter where permitted. Set both a maximum attempt count and an overall deadline. Before each attempt, check whether the fault is still transient and whether repeating the action could duplicate a side effect. Retryable writes need documented idempotency or dedupe protection.
Log Outcomes and Test Silent Failures
Log the same failure class and recovery decision used during execution. Include a correlation ID, operation ID and hashed idempotency key, alongside validation evidence, retry count and interval, authoritative post-action state and final outcome. Never log secrets or payment-card details. Redact sensitive values and restrict log access.[24][25] Minimise personal-data retention under applicable UK requirements.
Test empty success responses, missing pages, stale records, wrong-tenant results, unchanged post-action records and timeouts after writes. Each test must verify detection, correct classification, safe recovery and a log event that supports action - not just an error message.
Track semantic failure rates separately from transport errors. Also track unknown outcomes per 1,000 state-changing operations, duplicate actions and time to resolve unknown outcomes. Set alert thresholds using each tool’s measured baseline.
Conclusion: Validate Every Tool Boundary
The final check is not a tool response. It is proof that the requested change happened. A successful tool call confirms transport, not the business outcome. Before reporting completion, check the schema, completeness, business rules and post-action state against the authoritative system.
Keep transport success separate from business confirmation: transport_succeeded must not become business_outcome_confirmed until every check passes. Classify the finding, apply recovery within set limits and retain a redacted audit record of the evidence and final decision. This separation stops silent failures from passing as success.
When evidence is missing, explain what is known and what remains unconfirmed. Pause further side effects and route the case to reconciliation or human review. Do not move forward, retry blindly or claim success without evidence. Detecting silent failures means refusing to close the loop without proof.
FAQs
How do I choose business rules for each AI tool?
Keep business rules separate from schema validation. Valid data does not mean an action is permitted. Before changing state or processing a transaction, use your service layer to check order ownership, staff permissions, dispatch availability, refund eligibility and financial constraints against trusted server-side data.
For example, check amounts against the actual order - not just the tool input.
Return specific errors when business checks fail, and log them separately from formatting errors to maintain audit trails.
What if my tool has no way to verify changes?
If your tool can’t verify changes, don’t take apparent success at face value. Independently check the response against the expected schema. Check for completeness, truncation, correct data types, and missing or malformed fields. Apply business rules and eligibility checks, then confirm that the intended state change took place.
Treat timeouts as unknown outcomes and verify what happened before retrying. If you can’t complete the checks, stop or escalate. Add contract tests and regression cases to catch silent drift. [1][2][3]
How can I validate outputs without slowing my agent?
Automate deterministic checks outside the model’s reasoning path [1]. Route raw tool responses through a dedicated parser with strict schema validation to catch malformed responses, truncation or schema drift [2][3].
Use dependency graphs to ensure tasks run only after their prerequisites have been verified [4]. Keep validation separate from execution, and use idempotent retry handlers to preserve speed while letting only valid, complete results proceed [3][1][4][5].