All guides
Updated
Reading
9 min
By
Anlyon Team

How should an AI agent tool report pending, refused and unknown results so the model does not retry?

Map every action result to an explicit state and next step in the tool's return value, so an agent waits on approvals, observes pending work and never recreates an operation that may already have happened.

  • tool results
  • agent integration
  • outcomes
  • pending
  • retries
  • typescript

A tool that wraps a consequential action should return a structured result: the operation's id, its state, and the one next step the agent is allowed to take. "Error" is not a state. An agent that reads it will reasonably try again, and for an uncertain refund that is how one refund becomes two.

This guide maps every result an Anlyon action can return to an application-owned shape, with a complete TypeScript tool wrapper you can adapt.

TL;DR

  • Return operationId, state, nextStep and a plain-language message. Never a bare error.
  • Pending approval, a pending provider result and unknown are three different kinds of "not done".
  • Observe the existing record. Re-invoking with a fresh key is not polling.
  • A stable operationKey makes a repeated call return the existing operation.
  • Enforce in code. "Do not retry" in the message helps; the key and the scopes are the control.

Why does a bare error make an agent retry?

The model sees only what the tool returns. If an uncertain refund comes back as "Error: request failed", retrying is the most reasonable reading. The model has no way to know the refund may already exist at Stripe.

The fix has two halves. Communication: tell the model what is known and what to do next, in words. Enforcement: make the duplicate impossible regardless of what the model does, by persisting the business operation's key and keeping escalation tools away from the agent. A prompt saying "never retry refunds" is useful, but it is not an execution control.

What can an action invocation actually return?

An invocation has a status. A governed action (one with an adapter or a declaration) also creates an effect, and the invoke response carries its receipt grade. They describe different things, so read both.

StatusUsual gradeWhat it meansWhat the tool tells the agent
pending_approvalpendingParked until an approver decides. Nothing sentThe request is waiting for review. Do not ask again
runningpendingDispatching, or the provider accepted it and has not finishedIn progress. Observe the existing operation
succeededconfirmedDone, and a read-back or the provider's own record established itReport the specific verified result
succeededacknowledgedThe provider accepted it. Nothing read it backReport acceptance, with that limitation
unknownunknownNo usable response. Anlyon does not send it againMay have happened. Route to reconciliation. Never recreate
failedrefusedAnlyon stopped it before dispatch, for example an exhausted limitNot done. Report the boundary that stopped it
failedfailedThe provider rejected it, or it never left AnlyonNot done. Report the reason
denieddeniedThe approval was deniedNot done. Stop this request
expiredrefusedNobody decided before the approval expiredNot done. A fresh request needs a fresh review

Two details trip up wrappers. A refused or unknown invocation answers HTTP 200, with the result in the body, so a wrapper that checks only the HTTP status reports success. And an action with no adapter or declaration creates no effect, so grade is absent and succeeded means the destination answered 2xx, not that the business outcome was verified.

Is pending approval the same as a pending result?

No. There are three kinds of waiting, and an agent should be told which one it is in.

  • Pending approval. The invocation is parked with an approvalId. Nothing has been sent. approvals.waitForDecision() long-polls for a decision and returns the still-pending approval when your timeout elapses.
  • Provider result pending. The provider accepted the operation and has not finished it. A stripe.refund accepted as pending is read back up to 12 times. After that it stays unresolved until an operator resolves it. A Resend send is different: confirmation is Resend's record of the send, and delivery, bounces and complaints are not tracked.
  • Unknown. Evidence cannot establish what happened. This is not waiting for a known process to finish. It needs reconciliation.

A customer-facing message should keep them apart too: "refund requested" and "refund completed" are different sentences.

What should the tool return?

Define the shape in your application. This is not an Anlyon response type, it is the contract between your tool and your model:

{
  "operationId": "refund:rr_8812",
  "state": "unresolved",
  "nextStep": "operator_reconciliation",
  "message": "The refund may already have been issued. Do not create another refund. An operator will check Stripe.",
  "ref": { "invocationId": "inv_01J", "effectId": "eff_01J", "approvalId": null }
}

state is your vocabulary, chosen for the decisions your application makes. nextStep is a closed set the agent can act on. ref keeps the Anlyon ids so a later observation reads the same record.

A complete tool wrapper

The wrapper invokes the action once with a stable key, waits a bounded time for a decision, re-reads the invocation instead of invoking again, and maps the result.

import { Client, type InvokeResult } from '@anlyonhq/sdk';

const agent = new Client({ apiKey: process.env.ANLYON_AGENT_KEY! });

// Fail at startup if this key can do more than ask.
await agent.auth.requireScopes(['actions:invoke'], {
  forbidden: ['impact-limits:write', 'actions:resolve', 'approvals:decide', 'secrets:write'],
});

type State = 'awaiting_approval' | 'in_progress' | 'done' | 'not_done' | 'unresolved';
type NextStep = 'wait_for_approval' | 'observe' | 'report' | 'stop' | 'operator_reconciliation';

interface ToolOutcome {
  operationId: string;
  state: State;
  nextStep: NextStep;
  message: string;
  ref: { invocationId: string; effectId: string | null; approvalId: string | null };
}

function toOutcome(operationId: string, inv: InvokeResult): ToolOutcome {
  const ref = { invocationId: inv.id, effectId: inv.effectId ?? null, approvalId: inv.approvalId };
  const out = (state: State, nextStep: NextStep, message: string) => ({ operationId, state, nextStep, message, ref });
  const why = inv.decision?.explanation ?? inv.error ?? 'no reason recorded';

  switch (inv.status) {
    case 'pending_approval':
      return out('awaiting_approval', 'wait_for_approval', 'The refund is waiting for review. Tell the customer it is being reviewed. Do not ask again.');
    case 'running':
      return out('in_progress', 'observe', 'The refund was accepted and has not completed. Say it was requested, not completed. Do not ask again.');
    case 'succeeded':
      return inv.grade === 'acknowledged'
        ? out('done', 'report', 'Stripe accepted the refund. It has not been read back yet.')
        : out('done', 'report', 'The refund was issued and confirmed from Stripe.');
    case 'unknown':
      return out('unresolved', 'operator_reconciliation', 'The refund may already have been issued. Do not create another refund. An operator will check Stripe.');
    case 'denied':
      return out('not_done', 'stop', `The refund was not approved: ${why}. Do not retry.`);
    case 'expired':
      return out('not_done', 'stop', 'Nobody reviewed the refund in time. It was not issued. Do not retry.');
    case 'failed':
      return inv.grade === 'refused'
        ? out('not_done', 'stop', `The refund was refused before it was sent: ${why}. Do not retry.`)
        : out('not_done', 'stop', `The refund was not issued: ${why}.`);
  }
}

/** Re-read the invocation a bounded number of times. Never invoke again here. */
async function observe(invocationId: string, tries = 20): Promise<InvokeResult> {
  for (let i = 0; i < tries; i++) {
    const { data } = await agent.actions.invocation(invocationId);
    if (data!.status !== 'pending_approval' && data!.status !== 'running') return { ...data!, pendingApproval: false };
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
  const { data } = await agent.actions.invocation(invocationId);
  return { ...data!, pendingApproval: data!.status === 'pending_approval' };
}

export async function refundTool(input: { refundRequestId: string; paymentIntent: string; amount: number }) {
  // One persisted refund request, one key, however many times the model calls the tool.
  const operationId = `refund:${input.refundRequestId}`;

  const { data } = await agent.actions.invoke(
    'refund',
    { paymentIntent: input.paymentIntent, amount: input.amount, currency: 'usd' },
    { operationKey: operationId },
  );
  let inv = data!;

  if (inv.pendingApproval && inv.approvalId) {
    const decided = await agent.approvals.waitForDecision(inv.approvalId, { timeoutMs: 60_000 });
    if (decided.status === 'pending') return toOutcome(operationId, inv);
    inv = await observe(inv.id);
  } else if (inv.status === 'running') {
    inv = await observe(inv.id);
  }

  return toOutcome(operationId, inv);
}

What the wrapper does not do matters as much. It never calls invoke a second time for the same request. It never maps unknown to failed. It never offers the model a way to raise a limit, decide an approval or resolve an outcome: those scopes are checked as forbidden at startup.

How does the agent check on pending work later?

Give it a read-only tool that observes the stored record. Keep the invocation id in your own database against the business operation, then read it:

export async function checkRefund(operationId: string, invocationId: string) {
  const { data } = await agent.actions.invocation(invocationId);
  return toOutcome(operationId, { ...data!, pendingApproval: data!.status === 'pending_approval' });
}

If the model calls refundTool again instead, nothing new is sent: the same operationKey with the same request returns the existing effect. Reusing the key with a different request is refused with OPERATION_KEY_REUSE, which is the signal that the agent is trying to change an operation it already started.

Choose your application's wait time independently of the provider's. When your UI stops waiting, the operation does not stop existing. A closed browser tab should not erase the follow-up; keep the record and give an operator a route to it.

Which result needs which behavior?

Tool stateApplication behavior
awaiting_approvalSurface the existing review request. Notify, do not re-request
in_progressObserve the existing record on a schedule you choose
doneRecord the result and its grade against the business operation
not_doneClose the request. A new attempt is a new business decision with its own review
unresolvedKeep the operation open, block dependent steps, and assign reconciliation

A deliberate retry of a failed invocation is possible, and it is explicit: a new key and retryOf set to the failed invocation. It is refused while the original is unknown. That is an application decision, not something the model should improvise from an error message.

How do I test the mapping?

Exercise every row with controlled fixtures: an auto-approved call, a parked call that is approved, denied and left to expire, a limit refusal, a provider rejection, a pending provider result, and a lost response. For the last one, the lost-response model shows the accounting locally. Also test the tool being called twice for one refund request, and with the same id and a changed amount.

Frequently asked questions

What should a tool return to an LLM agent when an API call times out?
Return the existing operation id, the state unknown, and a next step that is not a retry, such as operator reconciliation. Say in plain words that the operation may already have happened. A bare error string invites the model to call the tool again, and a second call under a new key is a second refund or a second email.
What is the difference between pending approval and a pending provider result?
Pending approval means the request is parked until an approver decides, and nothing has been sent. A pending provider result means the provider accepted the operation and has not finished it, such as a Stripe refund in status pending. Both are not complete, and both should be observed through the existing record rather than invoked again.
How do I stop an agent from retrying a tool call that already ran?
Give each business operation a stable key persisted before the call, and pass it as the action's operationKey. A repeated call with the same key and the same request returns the existing operation without sending anything. The tool result should also say whether to retry, because the model reads that text, but the key is what enforces it.
Should the agent be able to raise its own limit when a tool is refused?
No. A refusal for an exhausted limit should be reported as final for this request. Keep limit changes and outcome resolution with an operator credential, and check at startup that the agent's key does not hold impact-limits:write or actions:resolve.

Let your agent act for your users, safely.

A few lines of server code, then send a user a connect link. Nothing to host.

$ claude mcp add --transport http anlyon https://api.anlyon.com/mcp