> ## Documentation Index
> Fetch the complete documentation index at: https://docs.botshield.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Set up BotShield for personal agents

> Step by step: get customers BotShield Verified, ask the account holder to approve exact terms through botshield.ai/approval, and check every order with the BotShield Signal API.

This guide sets up BotShield for personal agents in your Development environment, then moves it to Production:

* **The account holder's approval** of exact terms, through the `botshield.ai/approval` extension (steps 1 to 7).
* **The BotShield Signal API** at every order: verified, true or false (step 8).
* **Optional:** a passkey check in a signed-out session, through `botshield.ai/human-presence` (at the end).

Every BotShield call is made by your server with your secret key. For what each piece does, see [Personal agents (Poppy)](https://docs.botshield.ai/poppy/overview.md).

## What you need first

* **A working Poppy core.** Your `poppy.json`, verification of the signed `Poppy-Session` on each request, and Poppy's OAuth sign-in, so you know which of your accounts a request is for. See the [Personal Agent Protocol](https://personalagentprotocol.org). `@botshield/poppy` covers only BotShield's part, after those checks.
* **Node.js 20 or later**, or Cloudflare Workers.
* **[`@botshield/poppy`](https://www.npmjs.com/package/@botshield/poppy) 0.2.0 or later**, from npm. 0.2.0 adds `confirmLink` and runs on Cloudflare Workers; 0.1.0 does neither. The source is in [Bot-Shield/poppy-extensions](https://github.com/Bot-Shield/poppy-extensions).
* **A BotShield Console account** at [console.botshield.ai](https://console.botshield.ai).

```bash theme={null}
npm install @botshield/poppy@^0.2.0
```

## 1. Create a Development key

**1. Open your API keys**

In the Console, select **Development** in the header, then go to **Settings → Developer Tools → API Keys**. Create a key if you have none. It starts `bs_dev_`.

**2. Give it Gates API access**

On the key's row, check **Gates API access**. Approvals are sent with the Gates API, and you place Actions and gates with it below. See [Gates API](https://docs.botshield.ai/gate/gates-api.md#authentication).

**3. Turn on A link waits for my server's confirm**

On the same row, turn on **A link waits for my server's confirm**. A link made with this key is then not live at the tap: it goes live when your server confirms which account it is for (step 6). BotShield refuses a confirm for a different account than the one the link was started for.

Keep the key on your server, for example as `BOTSHIELD_SECRET_KEY`. Never send it to an agent or a browser.

## 2. Register a Trusted Agent

The approval card in the BotShield app is headed by the agent your request is sent under. Register one for your company:

1. Go to **Agents Ask → Agent registry** and select **Register Agent**, in **Development**.
2. **Agent name**: letters and digits only, for example `PersonalAgents`. You pass this name to `AccountHolderApproval` as `agent`.
3. **Display name**: what the person reads on the card, for example `Personal agents`.
4. **Allowed action categories**: any. Actions requests don't use them.

The Console shows an agent key once. You don't need it for these extensions: every call uses your secret key. See [Register an agent](https://docs.botshield.ai/agents-ask/register-an-agent.md).

## 3. Place your Action and your link gate

You need one BotShield Action for each kind of action that asks for approval, and one gate that makes your customers' accounts BotShield Verified. Place them with your Development key. You can also place them in the Console.

**1. The Action**

`POST /gates-api/actions/create`. The `actKey` is what you pass to `AccountHolderApproval` as `actionKey`.

```bash theme={null}
curl -s https://api.botshield.ai/operations/gates-api/actions/create \
  -H "Authorization: Bearer $BOTSHIELD_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"Refund to another card","actKey":"refund"}'
```

See [Place an action with the API](https://docs.botshield.ai/actions/place-an-action.md#with-the-gates-api).

**2. The link gate**

`POST /gates-api/create`. A gate that makes the account BotShield Verified on the tap, open to anyone:

```bash theme={null}
curl -s https://api.botshield.ai/operations/gates-api/create \
  -H "Authorization: Bearer $BOTSHIELD_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "link-account",
    "name": "Link your account",
    "policy": { "link": "required", "realDaysAtLeast": 0 },
    "activate": true
  }'
```

You use it once per customer, in step 6. See [The link setting](https://docs.botshield.ai/gate/link.md).

Check `data.error` on every answer. The environment comes from the key: a `bs_dev_` key places Development Actions and gates.

## 4. Publish `poppy.json`

List the extension under `extensions` in your `/.well-known/poppy.json`. Version 1 has no other fields.

```json theme={null}
{
  "protocol_version": "1.0",
  "organization": { "name": "Example Tickets", "domain": "tickets.example.com" },
  "apis": [
    { "type": "openapi", "url": "https://tickets.example.com/openapi.json", "description": "Orders and refunds" },
    { "type": "mcp", "url": "https://tickets.example.com/mcp", "description": "Orders and refunds" }
  ],
  "extensions": {
    "botshield.ai/approval": [{ "version": "1" }]
  }
}
```

If you add the optional passkey check (at the end), list `botshield.ai/human-presence` too. In a scope description, you can tell the person that the account holder approves each change in the BotShield app.

## 5. Add the server code

Create the API client and one handler per Action, once, at startup.

```typescript theme={null}
import {
  BotShieldApi, AccountHolderApproval,
  NotLinkedError, StillPerformingError, isTransient,
  approvalResponse, APPROVAL_ID_HEADER,
} from "@botshield/poppy";

const api = new BotShieldApi({ secretKey: process.env.BOTSHIELD_SECRET_KEY! }); // bs_…

const approvals = new AccountHolderApproval({
  api,
  agent: "PersonalAgents", // the Trusted Agent's name (step 2)
  actionKey: "refund",     // the Action's actKey (step 3)
});
```

### An action that needs the account holder's approval

Call `approvals.require()` on every request for the action, after your Poppy Session and access token checks. It starts the request for approval the first time, answers with its state on each repeat, and checks BotShield's signed answer once the account holder approves. `perform()` runs your action at most once.

```typescript theme={null}
app.post("/refunds", async (req, res) => {
  // After your Poppy Session and access token checks:
  // req.account.id is your own reference for the signed-in account,
  // req.poppy.clientId is the Personal Agent's client_id.
  const last4 = String(req.body.to_card_last4);
  const order = await getOrder(req.account.id, req.body.order_id);

  try {
    const r = await approvals.require({
      account: req.account.id,
      client: req.poppy.clientId,
      approvalId: req.get(APPROVAL_ID_HEADER),           // BotShield-Approval-Id
      meaning: { order: order.id, to: last4 },           // what the request asks for, as plain data
      summary: `Refund ${order.tickets} tickets to a **different card**, ending ${last4}.`,
      terms: [
        { label: "Show", value: order.show },
        { label: "Refund to", value: `Card ending ${last4}` },
        { label: "Total", value: order.total },
      ],
    });

    if (!r.approved) {
      const out = approvalResponse(r.approval);           // 403, with Retry-After while requested
      return res.status(out.status).set(out.headers).json(out.body);
    }
    res.json(await r.perform(() => refund(order, last4))); // at most once
  } catch (e) {
    if (e instanceof NotLinkedError) {
      // Not linked to BotShield: nothing was sent. Refuse, or offer the action another way.
      return res.status(403).json({ error: "account_not_linked" });
    }
    if (e instanceof StillPerformingError) {
      return res.status(503).set("Retry-After", String(e.retryAfter)).json({ error: "in_progress" });
    }
    if (isTransient(e)) {
      return res.status(503).set("Retry-After", "5").json({ error: "unavailable" });
    }
    throw e;
  }
});
```

* `meaning` decides whether a repeat is the same request. A request that asks for anything else starts a new request for approval, with a new `approval_id`.
* `terms`: 1 to 12 rows, each label up to 40 characters and each value up to 80. Every term that affects the action must be a row, including any total. The person reads them on their phone.
* `summary` is plain language, no links. Its first 90 characters, without formatting, head the card.
* Options: `ttlSeconds` (how long the person has to answer, 60–86400, default 600), `retryAfter` (default 5 seconds), `checkEvery` (BotShield is asked at most once per this many seconds per request, however often the agent repeats; default 10).
* A rate limit or an outage at BotShield leaves the request waiting. `isTransient()` tells you when a thrown error decided nothing.

### MCP tools

On an MCP server, return `approvalToolResult()` instead. It is an error result (`isError: true`) with text any MCP client can act on, and the object in `structuredContent`. Read the id back from the call's `_meta`:

```typescript theme={null}
import { approvalToolResult, APPROVAL_ID_META } from "@botshield/poppy";

// tools/call for "request_refund"
const r = await approvals.require({
  account, client, meaning, summary, terms,
  approvalId: params._meta?.[APPROVAL_ID_META] ?? params.arguments.approval_id ?? null,
});
if (!r.approved) return approvalToolResult(r.approval);
return { content: [{ type: "text", text: JSON.stringify(await r.perform(() => refund(order, last4))) }] };

```

An MCP client that does not know the extensions will not send `_meta`. Giving the tool an optional `approval_id` argument, and adding the id to the result's text, lets any model repeat the call with it. Without the id, `require()` still finds the request by what it means, within the same account and client.

### More than one server

The default store keeps state in memory, which suits one process. With more than one server or instance, pass a `store` that implements the `Store` interface on shared storage (Redis, Postgres, a Durable Object). Its `swap` must be atomic per id: that is what keeps an action to at most once.

```typescript theme={null}
const approvals = new AccountHolderApproval({ api, agent: "PersonalAgents", actionKey: "refund", store: myApprovalStore });
```

## 6. Get each customer BotShield Verified once

The account holder can be asked only once their account is BotShield Verified. Get each customer BotShield Verified once, from a signed-in page of yours, with the link gate from step 3:

```typescript theme={null}
// Start: the customer is signed in, so you know their account.
const check = await api.startGateCheck({ gate: "link-account", partnerUserRef: account.id });
// Show check.web_url (a link on app.botshield.ai) or a QR code of it. Keep check.request_id.

// After the customer confirms in the BotShield app, confirm the link from your server:
const state = await api.confirmLink({ requestId: check.request_id, partnerUserRef: account.id });
// 'live'      linked: approvals for this account now reach the customer's phone
// 'not_done'  the customer has not confirmed yet; try again shortly
// 'pending'   or 'not_live': the link did not go live; start again
```

`confirmLink` collects the finished token and checks it once with the account your session shows, which confirms the link that waits for your server. Send the same `partnerUserRef` you pass to `approvals.require()` as `account`.

A customer who is not BotShield Verified gets `NotLinkedError` from `approvals.require()`, and nothing reaches anyone.

## 7. Test it

With your Development key, against `https://api.botshield.ai`, and the BotShield app on your own phone:

* [ ] `GET /.well-known/poppy.json` lists `botshield.ai/approval`.
* [ ] Get a test account BotShield Verified (step 6). `confirmLink` answers `live`.
* [ ] Ask for the action. Your server answers 403 with `account_holder_approval_required`, `state: "requested"` and `Retry-After`. A card arrives in the BotShield app, headed by your agent's display name, with your summary and terms.
* [ ] Repeat with `BotShield-Approval-Id` before you answer: the same object, still `requested`.
* [ ] Approve with your passkey, then repeat: the action is performed. BotShield is asked at most once per `checkEvery` (10 seconds by default), so a repeat right after you approve can still read `requested`.
* [ ] Repeat again: the first result comes back, and the action is not performed again.
* [ ] Ask again and decline in the app: `state: "declined"`, nothing done. Let one expire: `state: "expired"`.
* [ ] Ask for the action with an account that is not BotShield Verified: `NotLinkedError`, no card sent.
* [ ] Call the action as an MCP tool from an ordinary MCP client: the tool error text tells the model what to do, and the repeated call succeeds.

The [live demo](https://poppy-demo.couchtour.app) runs this flow, and its source is in [`demo/couchtour`](https://github.com/Bot-Shield/poppy-extensions/tree/main/demo/couchtour).

## 8. Check every order with the BotShield Signal API

When a customer's own agent places orders on their account, check each one. The first time, the account holder approves the agent once, with their passkey. After that, your server asks at every order and gets **verified: true** or **false**, and nobody waits. The account holder can remove the agent in the BotShield app, and the next check answers false.

It uses the same key, the same BotShield Verified customers and the same `botshield.ai/approval` extension. See [BotShield Signal API](https://docs.botshield.ai/poppy/agentic-checkout.md) for the calls.

## 9. Go to production

1. **A Production key.** Create a `bs_production_` key, check **Gates API access** (you confirm with your Developer passkey), and turn on **A link waits for my server's confirm**.
2. **A Production Trusted Agent.** Register it under **Production**. Agents do not move between environments.
3. **Production Action and link gate.** Place them again with the Production key. A Production gate activates only when your business is verified, you have a verified domain, and your plan has room. See [Go to production](https://docs.botshield.ai/gate/go-to-production.md).
4. **Shared storage.** Pass a `store` on shared storage if you run more than one instance.
5. **Get your customers BotShield Verified** with the Production key and the Production link gate (step 6).
6. **Swap the key** on your server and publish `poppy.json` on your production domain.

## Optional: a passkey check in a signed-out session

For an action in a session with **no signed-in account**, the account holder's approval doesn't apply: there is no BotShield Verified account to ask. `botshield.ai/human-presence` asks for a passkey confirmation on a phone instead, under a rule you set at one of your gates. For example: one free trial per verified phone number. For a signed-in account, use the approval above.

**1. Place the gate**

`POST /gates-api/create`. No BotShield Verified step, no sign-up list, and one pass per verified phone number, ever:

```bash theme={null}
curl -s https://api.botshield.ai/operations/gates-api/create \
  -H "Authorization: Bearer $BOTSHIELD_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "free-trial",
    "name": "Free trial",
    "policy": {
      "link": "never",
      "signedUp": false,
      "passesPerPerson": { "limit": 1, "window": "ever" }
    },
    "activate": true
  }'
```

The `key` is what you pass to `HumanPresence` as `gate`. See [The policy document](https://docs.botshield.ai/gate/gates-api.md#the-policy-document) and [Who may pass](https://docs.botshield.ai/gate/who-may-pass.md).

**2. Declare it**

Add `"botshield.ai/human-presence": [{ "version": "1" }]` under `extensions` in your `poppy.json`.

**3. Check it on the request**

Call `presence.require()` with the verified Poppy Session. A pass belongs to that Session (`client_id`, `sid` and User ID) for `passFor` seconds (default 3600), and is good for this gate only.

```typescript theme={null}
import { HumanPresence, presenceResponse, PRESENCE_ID_HEADER, isTransient } from "@botshield/poppy";

const presence = new HumanPresence({ api, gate: "free-trial" });

app.post("/trials/start", async (req, res) => {
  try {
    const r = await presence.require({
      session: { client: req.poppy.clientId, sid: req.poppy.sid, user: req.poppy.userId },
      presenceId: req.get(PRESENCE_ID_HEADER),           // BotShield-Presence-Id
    });
    if (!r.passed) {
      const out = presenceResponse(r.presence);           // 403 with verification_uri while requested
      return res.status(out.status).set(out.headers).json(out.body);
    }
    res.json(await startTrial(req.body));                 // passed the gate's rule
  } catch (e) {
    if (isTransient(e)) return res.status(503).set("Retry-After", "5").json({ error: "unavailable" });
    throw e;
  }
});
```

While the check waits, the presence object carries `verification_uri`, a link on `app.botshield.ai`. The agent shows the link, or a QR code of it, and must not open it itself. If the gate's rule refuses it, for example because this verified phone number already started a trial, the state is `refused` and nothing is done. On an MCP server, return `presenceToolResult(p.presence)` and read the id from `_meta[PRESENCE_ID_META]`.

**4. Test it**

Start a trial: your server answers 403 with `human_presence_required` and a `verification_uri`. Open the link on your phone, confirm, repeat: the trial starts. Start another from a new Session with the same phone: `state: "refused"`.

## Next steps

> [card] [Personal agents (Poppy)](https://docs.botshield.ai/poppy/overview.md)
>
> What the extensions do, and what each side learns.

> [card] [Gates API](https://docs.botshield.ai/gate/gates-api.md)
>
> Place and run gates from your server.

> [card] [BotShield Actions](https://docs.botshield.ai/actions/overview.md)
>
> Actions and the act string.

> [card] [@botshield/poppy on npm](https://www.npmjs.com/package/@botshield/poppy)
>
> The package and its versions.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.