thelastapi
Get started free

Agent-friendly APIs: errors that say what to do next

API error design for AI agents requires machine-readable reason codes, explicit missing permissions, and actionable next steps in every response.

On this page 7 sections

Agent-friendly API error design provides structured reason codes, explicit missing permissions, and unambiguous next steps directly in the error response. When an AI agent encounters a generic HTTP status like 403 Forbidden without context, it often gets stuck in retry loops, hallucinates non-existent parameters, or asks a human for raw credentials. Providing machine-readable fields such as details.reason and details.next_step allows agents to self-correct, poll until dependencies finish, or hand an approval link directly to the user.

This guide outlines how to design API errors that autonomous agents can reliably handle, using the error architecture from thelastapi as a reference implementation.

Why traditional API errors break AI agents

Human developers read documentation when an API returns an error. Autonomous agents running in Claude Code, Codex, or Cursor rely almost entirely on the text returned in the HTTP response body or tool output.

Standard REST APIs typically fail agents in three distinct ways:

  • Vague status messages. A payload like {"error": "Forbidden"} does not tell the agent whether the resource does not exist, the token is invalid, or the caller lacks a specific privilege. The agent cannot know if retrying with different parameters will help.
  • Dead-end errors. An error that says Payment method required leaves an agent stranded. An agent cannot enter card details directly, nor should it try to prompt a human for raw numbers in a chat window.
  • Unstructured advice. Human-written error strings like "Please upgrade your plan on the billing settings page" force an LLM to parse natural language, guess URLs, or hallucinate the navigation steps required.

To keep an agent productive, an error response must function as an instruction. It needs to tell the agent what happened, whether retrying will ever succeed, and what specific action or URL will resolve the block.

The anatomy of an actionable error payload

An agent-friendly error payload combines standard HTTP status codes with structured metadata. In thelastapi, operations that fail return a JSON response containing an error identifier, a human-readable message, and a details object containing instructions.

Here is what a Limited key receives when attempting an operation reserved for the account owner, such as reading production database credentials:

JSON
{
  "error": "forbidden",
  "message": "This key does not have permission to read the production database.",
  "details": {
    "reason": "owner_only",
    "permission": "database.production:read",
    "key_id": "key_agent_growth",
    "grant_url": "https://thelastapi.dev/keys/key_agent_growth/allow?permission=database.production:read",
    "console_url": "https://thelastapi.dev/projects/prj_123/database",
    "key_url": "https://thelastapi.dev/keys?key=key_agent_growth",
    "next_step": "Give the user details.grant_url so they can allow this permission for this key, then retry."
  }
}

Notice how this structure changes the agent's behavior:

  1. details.reason categorizes the failure immediately. The agent knows this is an owner_only restriction, not an invalid request body or an outage.
  2. details.permission names the exact grant required (database.production:read).
  3. details.grant_url provides a targeted link where the human owner can click Allow just this, grant Read everything, or elevate the key.
  4. details.next_step gives the model a clear operational instruction: do not retry immediately; present the grant URL to the user, and wait.

For more details on key tiers and permission scopes, see Keys and environments.

Standard errors and their recovery paths

Every common failure mode should map to a defined recovery path. If an agent cannot recover on its own, the error must tell it how to delegate to the human operator.

HTTP StatusCodeReasonWhat the agent should do
401unauthorizednot_logged_inRun npx @vibiz/cli login and show the user the verification link.
400invalid_requestsignup_closedStop retrying. Give the user waitlist_url (https://thelastapi.dev/start).
403forbiddenowner_onlyStop retrying. Present details.grant_url or details.console_url to the owner.
409dependency_not_readyprovisioningWait and poll GET /v1/projects/:id/dev until status is ready.
404not_foundproject_missingCheck the project id in ./vibiz.json or run vibiz projects.

Handling asynchronous provisioning (409)

When creating projects or resources via POST /v1/projects, resources provision in the background. A subsequent request to fetch environment variables before provisioning finishes returns a 409 dependency_not_ready.

Instead of failing outright, the error informs the agent that the system is still working. The agent can parse the status, pause, and poll GET /v1/projects/:id/dev until it transitions from provisioning to ready.

Handling closed sign-ups (400)

When new sign-ups are closed and someone without an account attempts to sign up via the CLI or MCP server, the endpoint returns:

JSON
{
  "error": "invalid_request",
  "message": "This email can't open a new account yet.",
  "details": {
    "reason": "signup_closed",
    "waitlist_url": "https://thelastapi.dev/start",
    "next_step": "Stop retrying. Provide the user with details.waitlist_url."
  }
}

This prevents the agent from re-running vibiz login or repeatedly trying alternative flags.

Keeping secrets out of chat context

A major challenge in API error design for agents is handling missing secrets. If an API simply returns {"error": "Missing EXTERNAL_API_KEY"}, an agent might prompt the user directly in chat: "Please paste your API secret key here."

Putting secrets into conversational prompts exposes them to model training, context logs, and shell histories. APIs designed for agents avoid this by separating secret collection from the chat interface.

Instead of demanding the secret in the request, the platform provides a dedicated tool and route:

Terminal
curl -X POST https://thelastapi.dev/v1/projects/prj_123/secret-link \
  -H "Authorization: Bearer $VIBIZ_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "EXTERNAL_API_KEY", "environment": "production", "kind": "env"}'

The response returns a single-purpose, authenticated link:

JSON
{
  "console_url": "https://thelastapi.dev/projects/prj_123/secrets/new?name=EXTERNAL_API_KEY&env=production&kind=env",
  "instruction": "Paste EXTERNAL_API_KEY here: https://thelastapi.dev/projects/prj_123/secrets/new?name=EXTERNAL_API_KEY&env=production&kind=env . It goes straight to thelastapi, never through this chat."
}

The agent hands this link to the human user. The user enters the secret in the browser, where it is encrypted and pushed directly to the hosting infrastructure. The agent never sees the secret value. Learn more about human authorization patterns in Owner approvals: a human in the loop for agents that post, spend and file.

How agents parse and execute error responses

When coding agents interact with toolkits through the Model Context Protocol (MCP) or an HTTP SDK, they parse response bodies to make control flow decisions.

Here is an example using Node.js to illustrate how an agent workflow can consume structured errors:

TypeScript
import { vibiz } from '@vibiz/app';

async function performTask(projectId: string) {
  const response = await fetch(`https://thelastapi.dev/v1/projects/${projectId}/env`, {
    headers: { Authorization: `Bearer ${process.env.VIBIZ_API_KEY}` }
  });

  if (!response.ok) {
    const errorData = await response.json();

    if (response.status === 403 && errorData.details?.reason === 'owner_only') {
      // The agent halts execution and prompts the user with the action link
      console.log(`Action blocked: ${errorData.message}`);
      console.log(`Next step: ${errorData.details.next_step}`);
      console.log(`Approve this permission here: ${errorData.details.grant_url}`);
      return;
    }

    if (response.status === 409 && errorData.error === 'dependency_not_ready') {
      console.log('Environment is still provisioning. Polling project status...');
      // Initiate polling loop against GET /v1/projects/:id/dev
      return;
    }

    throw new Error(`Unhandled API error: ${errorData.message}`);
  }

  return await response.json();
}

By inspecting errorData.details, the agent avoids blind retries. For gateways that manage multiple foundation models, consistent error shapes are equally essential; see LLM API errors explained: 429, 503 and context length for rate limit handling across providers.

Teaching workflows with skills and MCP

Clear errors solve problems when things fail, but providing operational context beforehand prevents errors entirely. thelastapi implements this through two interfaces:

  1. The vibiz_docs MCP tool: Coding agents can invoke vibiz_docs with topics like keys, payments, or connectors before calling mutating actions. This lets them verify arguments and permission requirements beforehand.
  2. Installable Skills bundles: Running vibiz skills add --global installs workflow definitions into .claude/skills, .agents/skills, or .cursor/skills. These markdown files teach Claude Code, Codex, and Cursor how the API behaves and how to handle limited access keys.

When skills, MCP tools, and actionable error responses work together, an agent can manage infrastructure, databases, and deployments with a single key without crashing into permission barriers. For a complete guide to running full-stack apps with one key, read One API key for an AI agent: hosting, database, email, payments and models.

To connect your coding agent and test structured error handling in a sandbox, review the Agents documentation or follow the steps in Agent skills.

Frequently asked questions

Why shouldn't an API simply return a standard 403 Forbidden status?

A plain 403 status tells the agent that an action is blocked, but not why or how to resolve it. Without structured fields like missing permissions or grant URLs, agents often guess parameters, retry needlessly, or fail completely.

How should an agent handle an owner_only error?

The agent should halt the blocked operation, output the message from `details.next_step`, and present `details.grant_url` to the user so the human owner can approve the specific permission.

What happens when an agent hits closed sign-ups?

The endpoint returns `400 invalid_request` with `details.reason: "signup_closed"` and `details.waitlist_url`. The agent is instructed to stop retrying and present that link to the user.