Agent Architecture

AI Agent Tool Design: Schemas, Contracts, and Error Semantics

Design reliable AI agent tools with precise schemas, bounded permissions, structured results, and error contracts that handle retries and uncertain outcomes.

· · 7 min read

Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.

An AI agent tool is an executable contract between a model's proposed action and an application's real capabilities. Good tool design makes the intended action easy to select, invalid requests easy to reject, and uncertain outcomes possible to investigate. A descriptive function name helps, but reliability depends on the entire contract: inputs, authority, preconditions, effects, outputs, and recovery.

This guide develops an illustrative order-cancellation interface. The schemas and operational policies are proposed engineering designs, not a tested SDK implementation or a claim that one interface fits every business.

Start with a bounded business capability

A generic execute_api_request tool transfers endpoint selection, payload construction, and recovery decisions to the model. For a support agent that cancels orders, a narrower interface can make those decisions explicit. Begin with orders_get_cancellation_options and orders_cancel, rather than exposing an unrestricted HTTP client.

Anthropic's tool-design guidance recommends deliberate tool selection, clear namespaces, meaningful returned context, and evaluation with realistic tasks. Those are design principles rather than universal evidence that fewer tools always improve performance. Read the primary guidance.

For the proposed cancellation interface, write down what success means before writing the schema: the specified eligible order is canceled once, the actor had permission at execution time, and the result identifies whether a refund was initiated. “The API returned successfully” is too weak because the response might acknowledge a queued request rather than a completed cancellation.

Separate capabilities when their authority differs. Looking up cancellation eligibility should not require permission to cancel. Conversely, avoid making the model assemble ten low-level steps when one server-side business operation can enforce their shared invariant.

Make the input schema restrictive and descriptive

A schema describes admissible structure. JSON Schema object properties are optional unless listed in required, and extra properties remain permitted unless constrained. Set those choices explicitly instead of assuming a typed-looking object closes the contract. JSON Schema object reference.

An illustrative input schema could be:

{
  "type": "object",
  "properties": {
    "order_id": {
      "type": "string",
      "minLength": 1,
      "maxLength": 80,
      "description": "Exact order identifier returned by the order lookup tool."
    },
    "reason": {
      "type": "string",
      "enum": ["customer_request", "duplicate_order"]
    },
    "expected_version": {
      "type": "integer",
      "minimum": 0,
      "description": "Order version observed during eligibility lookup."
    }
  },
  "required": ["order_id", "reason", "expected_version"],
  "additionalProperties": false
}

This schema intentionally omits credentials, tenant identifiers, and a Boolean approved field. The executor should obtain identity and tenant scope from authenticated execution context. A model-supplied approved: true is a statement, not evidence of authorization.

Describe identifier provenance, units, and boundary behavior. If a tool accepts money, specify integer minor units and currency rather than an ambiguous floating-point amount. If search accepts dates, state the timezone and whether the end boundary is inclusive. These details reduce interpretation at the point where interpretation can create effects.

Schema validation still cannot establish that an order belongs to the actor, remains cancelable, or matches the customer's intended order. Those checks belong in application logic. The distinction also appears in structured-output validation.

Treat the description as a decision interface

The model needs to know when to choose a tool and when to avoid it. A useful description for this example would say: “Cancel one eligible order after explicit customer authorization. Requires the exact order identifier and version from eligibility lookup. Does not modify addresses or cancel subscriptions. A pending result requires status lookup.”

Specify the ambiguous cases. Does “stop my next delivery” mean cancel an order, skip a subscription shipment, or pause a subscription? The tool catalog should make that distinction discoverable. If the user's request does not identify which outcome they want, the agent should clarify rather than infer a destructive interpretation.

A description can guide behavior, but it cannot enforce a safety boundary. The backend must reject a cancellation outside its permitted scope even when the model produces a persuasive rationale.

Return machine-usable results with evidence

An output should distinguish successful completion from intermediate progress. For this proposed interface, use a tagged result such as:

{
  "status": "pending",
  "operation_id": "op_example_42",
  "order_id": "order_example_19",
  "observed_order_version": 7,
  "next_action": "check_operation_status"
}

A completed branch might instead include status: "canceled", an authoritative cancellation identifier, and a separate refund state. Keep the distinction between cancellation and refund settlement visible; one does not prove the other.

MCP's versioned tool specification supports inputSchema, optional outputSchema, and structured results. Where an output schema is declared, the specification requires conforming structured results and recommends client validation. It also distinguishes protocol errors from tool execution errors reported through isError. This protocol structure does not define your application's cancellation policy. MCP tools specification, 2025-11-25.

Return sufficient evidence for the next decision, not a complete internal record. A status, operation identifier, relevant version, and concise explanation are usually more useful than a raw database object containing unrelated personal information. Ensure the model never has to scrape a human-oriented success sentence to recover the operation identifier.

Define errors by recovery action

A single success: false response collapses very different conditions. In the proposed contract, map failures to actions:

Error class What it means here Allowed recovery
INVALID_ARGUMENT Request fails structural or semantic validation Correct specified fields; bounded attempts
NOT_AUTHORIZED Actor cannot perform this action Stop or obtain a legitimate authorization change
VERSION_CONFLICT Relevant order state changed Read current state and reconsider
RATE_LIMITED Service rejected admission Wait within the run's deadline
OUTCOME_UNKNOWN Request might have reached the service Reconcile by operation identity

This table is a suggested application taxonomy, not a standard error vocabulary. Include safe, actionable details such as the invalid field or next retry time. Exclude stack traces, credentials, and unrelated customer data from the model-facing response.

Never label a timeout as a definite failure unless the system can prove no effect occurred. HTTP defines idempotence in terms of repeated requests having the same intended effect; it cautions against automatically retrying non-idempotent requests without a basis for knowing repetition is safe. RFC 9110, section 9.2.2.

Walk through an ambiguous cancellation

Consider a hypothetical customer who asks to cancel order A. The agent reads eligibility and observes order version 7. The application records the authorized action and assigns a stable operation key before submitting the cancellation. That key belongs to the logical action, not a newly generated model response.

The request times out. The agent cannot truthfully report either “canceled” or “not canceled.” The executor queries the operation ledger using the same action identity. If the ledger confirms cancellation, it returns the recorded result. If the order is now dispatching, the application returns the updated state and blocks an obsolete cancellation attempt.

If reconciliation is unavailable, the workflow moves to an explicit unknown-outcome state and human review. It should not manufacture a fresh key and try again. A stable key also needs server-side enforcement: scope it to the tenant, store a hash of the normalized action payload, and reject reuse with different arguments. Otherwise a key can silently refer to a different cancellation.

An implementation must define the retention period for operation records and the behavior after expiry. Retaining keys briefly while retrying for much longer creates a duplication window. See idempotency for agent actions for the broader recovery design.

Validate the contract against failure cases

Evaluate tools at two levels. Contract checks should exercise invalid arguments, authorization failures, stale versions, duplicate requests, malformed results, and missing operation records. Agent-level tasks should test whether the model selects the correct capability, requests clarification for ambiguous intent, and reports pending or unknown states accurately.

Inspect side effects in addition to final answers. A fluent apology can conceal two cancellations. A correct final sentence can follow an unauthorized lookup. For this example, assert which order changed, how often the mutation occurred, which actor authorized it, and what evidence supported the user-facing claim.

Version the interface when semantics change. Renaming a field is obvious; changing “cancel request accepted” into “order canceled” without changing the response contract is more dangerous because old workflows can misinterpret it. Keep fixtures for each supported version until in-flight runs finish or are migrated.

Frequently asked questions

Should every backend endpoint become a tool?

No. Expose the capabilities needed for actual tasks, with clear business meaning and enforcement. An endpoint can remain internal when its safe use depends on orchestration the model should not control.

Does strict JSON prevent unsafe tool use?

It prevents some invalid structures. Authorization, intent matching, current-state checks, and effect verification require additional application controls. A perfectly valid identifier can still point to the wrong order.

Can the agent choose whether to retry?

It can propose recovery, but the executor should enforce retry classes, action identity, deadlines, and budgets. Reserve uncertain mutation outcomes for reconciliation rather than unconstrained regeneration.

Source reference list

AI Agents
Tool Design
JSON Schema
Agent Reliability