---
name: adding-approvals-to-code
description: Use when the user wants an AI agent, bot, script or automation they are building to ask a person before risky actions (sending, paying, deleting, deploying, changing access), or mentions human-in-the-loop, approval steps, or VariantGate in code. Finds the risky actions in the codebase and puts an approval check in the code that performs each one, so the model cannot skip it.
---

# Adding approvals to code

The user is building something that acts on its own, and wants a person to say yes before the risky parts happen. VariantGate is the approvals service: the code asks, a person answers in an inbox (or a standing rule answers for them), and the code acts only on a yes. Your job is to put that check into the code, in the right places.

## The one rule

The code acts only when the answer has `allowed: true`. Pending, denied, expired, withdrawn, a timeout and an error all mean the action does not happen. Never write a fallback that acts when the service cannot be reached.

## 1. Find the actions worth asking about

Search the codebase for side effects, not for model calls. Look for:

- sending email, messages, posts or notifications (SMTP clients, Slack, Twilio, social APIs)
- moving money (Stripe, PayPal, bank or invoicing APIs, refunds)
- deleting or overwriting data (DELETE queries, `rm`, bucket deletes, `drop`)
- deploying, migrating, changing infrastructure or DNS
- changing who can access what (roles, sharing, API keys)

List what you found with file and line, and ask the user which ones should need approval. Reading, searching and drafting do not.

## 2. Name each action

Give each a short dotted name, family first: `email.send`, `payment.create`, `payment.refund`, `files.delete`, `deploy.production`. Standing rules match on these names, including families such as `payment.*`, so keep them consistent across the codebase.

## 3. Put the check where the action happens

Wrap the function that performs the action, not the prompt and not the tool description. A check in a prompt is a request to the model; a check in code is a guarantee.

Both SDKs are served from the VariantGate site until they are on npm and PyPI (as `@variantgate/agent` and `variantgate`). The Python client and the `variantgate` command read `VARIANTGATE_KEY` and `VARIANTGATE_API_URL` from the environment; the TypeScript client takes them as options, as below:

```sh
npm install https://variantgate.com/sdk/variantgate-agent-latest.tgz
pip install https://variantgate.com/sdk/variantgate-latest.tar.gz
```

**TypeScript**, with the `@variantgate/agent` package:

```ts
import { ApprovalClient } from "@variantgate/agent";

const approvals = new ApprovalClient({
  agent: "billing-bot",
  apiUrl: process.env.VARIANTGATE_API_URL ?? "https://api.variantgate.com",
  key: process.env.VARIANTGATE_KEY!,
});

export async function refund(order: Order) {
  return approvals.guard(
    {
      action: "payment.refund",
      summary: `Refund €${order.total} to ${order.customerEmail} for order ${order.id}`,
      amount: order.total,
      currency: "EUR",
      details: { order: order.id, reason: order.refundReason },
    },
    () => stripe.refunds.create({ payment_intent: order.paymentId })
  );
}
```

`guard` asks, waits for the answer, runs the function only on a yes, reports whether it succeeded, and throws `NotApprovedError` otherwise. Catch that where the agent can tell the user what was refused.

A person may approve a narrower version: new wording, or a lower amount. Then `changed` is `true`, and only `approved_summary`, for at most `approved_amount`, may be done. By default `guard` does nothing on such an answer and throws `ChangedApprovalError`, a kind of `NotApprovedError`. When the code can do the narrower version, pass `{ acceptChanges: true }` and use the decision `guard` hands the function: `(approved) => refundAmount(order, approved.approved_amount)`.

**Python**, with the `variantgate` package (3.9 or newer):

```python
from variantgate import require_approval

@require_approval(
    "payment.refund",
    lambda order: f"Refund €{order.total} to {order.customer_email} for order {order.id}",
    amount=lambda order: order.total,
    currency="EUR",
    details=lambda order: {"order": order.id, "reason": order.refund_reason},
)
def refund(order):
    return stripe.Refund.create(payment_intent=order.payment_id).id
```

`require_approval` works on plain and `async` functions and as a `with` block. Anything but a yes raises `NotApprovedError`, and so does an approval with changes (`ChangedApprovalError`) unless you pass `accept_changes=True` and act on `approved_summary` and `approved_amount`; an unreachable service raises `ApprovalApiError`, and a key that may not ask for the action raises its subclass `OutOfScopeError`, which retrying never fixes; both are `VariantGateError`. In an agent tool, catch `VariantGateError` and return the refusal to the model as text.

**Any other language**, over HTTP with the key as `Authorization: Bearer …`:

1. `POST /v1/requests` with `agent`, `action`, `summary`, optional `details`, `amount` and `currency`, and `wait_seconds: 30`.
2. While `status` is `pending`: `GET /v1/requests/{id}?wait_seconds=30`.
3. Act only if `allowed` is `true`, and only on `approved_summary` and `approved_amount`. When `changed` is `true` and the code cannot do the narrower version, do not act.
4. Then `POST /v1/requests/{id}/outcome` with `outcome` (`succeeded` or `failed`) and a short `note`.
5. If the code stops waiting, `POST /v1/requests/{id}/withdraw`.

**Shell scripts and CI**: `variantgate run --action deploy.production --summary "Deploy v2.14 to production" -- ./deploy.sh` runs the command only after a yes and passes on its exit code. On an approval with changes it does not run the command and exits 3. Either package installs the command; without installing, use `npx -y https://variantgate.com/sdk/variantgate-agent-latest.tgz run …`.

## 4. Write summaries a person can decide on

One sentence saying exactly what will happen, built from the real values: who receives it, how much, how many. "Refund €49.00 to ana@example.com for order 1182", not "Process refund". Pass money as `amount` and `currency` as well, because rules with a limit go by those fields.

## 5. Keep the key out of the code

Read `VARIANTGATE_KEY` (and `VARIANTGATE_API_URL`, when not using the hosted service) from the environment or the secret store. Never commit a key. Use one key per agent, so each can be revoked and ruled on separately.

## 6. Test that refusals hold

For each wrapped action, add a test where the approval is denied (or the service fails) and assert the side effect did not happen. Stub the client; do not call the real service from tests.

## 7. Suggest standing rules

Tell the user which requests will be routine, so a workspace owner can answer them in advance under Rules: "always allow `email.send`", "always ask about `payment.*` above €50", "never allow `files.delete`". You cannot write rules with an agent key, and should not try.
