RiskboundDocs

Onboarding guide

3. Quickstart with the SDK

In this page you will:

  1. check your keys,
  2. register your agent,
  3. write your first policy,
  4. wrap the refund action with guard(), in TypeScript or Python,
  5. see allow, ask and block in the dashboard.

Before you begin#

You need three values: your Riskbound URL, an admin key and an agent key. On a hosted Riskbound we give you the URL and the admin key. Running it yourself, the admin key is the one the API printed on its first start (see below). Put them in your shell:

bash
export RISKBOUND_URL=https://<your Riskbound URL>
export RISKBOUND_ADMIN_KEY=rb_admin_...
export RISKBOUND_API_KEY=rb_agent_...
  • The admin key is for people and setup: rules, agents, approvals. Keep it out of agent code.
  • The agent key is for the agent. It can ask for decisions and nothing else. It cannot approve its own requests.

Make the agent key yourself with the admin key, on the dashboard's Keys page or with the API:

bash
curl -s -X POST "$RISKBOUND_URL/v1/keys" \
  -H "Authorization: Bearer $RISKBOUND_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "support-bot", "role": "agent"}'

The answer holds the key in key. Each key is shown once. Riskbound keeps only a hash of it, so nobody can read it back. Keep both keys in your secret store. GET /v1/keys lists your keys by name and prefix, with when each was last used, and POST /v1/keys/<id>/revoke revokes one.

Trying it on your laptop first? Run the backend from the repo with the steps in the main README, in self-host mode. Its first start prints an admin key in the logs. Set RISKBOUND_URL=http://localhost:8200, make an agent key as above, and go on with step 1. Or open the dashboard: its first-run page at /setup makes the agent key, registers support-bot and loads the refund policy, which are steps 2 and 3 below. Running step 2 again then answers Agent "support-bot" is already registered, which is fine.

Step 1. Check your keys#

bash
curl -s "$RISKBOUND_URL/v1/auth/key" -H "Authorization: Bearer $RISKBOUND_API_KEY"

You should see your tenant id and the key's role:

json
{"tenantId":"3231bacf-...","role":"agent"}

A 401 means the key is wrong or has been revoked.

Step 2. Register the agent#

Every agent must be registered before it can act. An unknown agent is always blocked. Registration also sets the agent's limits.

bash
curl -s -X POST "$RISKBOUND_URL/v1/agents" \
  -H "Authorization: Bearer $RISKBOUND_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{"key": "support-bot", "name": "Support bot", "daily_spend_cap_minor": 200000, "rate_per_minute": 30}'
FieldMeaning
keyThe name your code uses. Lowercase letters, digits, - and _
nameA name people read in the dashboard
daily_spend_cap_minorMost the agent may spend in a day, in cents. 200000 is $2,000. It counts the amount_minor param
rate_per_minuteMost actions per minute

Amounts are always whole numbers in minor units, such as cents. $480.00 is 48000. Riskbound rejects fractions.

Step 3. Write your first policy#

A policy is your rules, written in Cedar. Start from the refund policy. Save it as refunds.cedar:

cedar
// Refunds up to $100 go through.
@id("refund-small")
permit (principal, action == Action::"act", resource == Tool::"refund")
when { context.amount_minor <= 10000 };

// Refunds up to $500 wait for a person.
@id("refund-needs-approval")
permit (principal, action == Action::"act_with_approval", resource == Tool::"refund")
when { context.amount_minor <= 50000 };

// Refunds over $500 never run.
@id("refund-hard-cap")
forbid (principal, action, resource == Tool::"refund")
when { context.amount_minor > 50000 };

How to read it:

  • Tool::"refund" is the tool name your code passes to guard().
  • context holds the params your code sends, so context.amount_minor is the amount.
  • Action::"act" means allow. Action::"act_with_approval" means ask_human. A forbid always wins over a permit.
  • If nothing permits the action, it is blocked. You never have to list everything that is not allowed.
  • The @id is the reason recorded with each decision. Pick ids a person can read.

Policies are never edited. Each change is a new version, and you choose when a version goes live. There are three steps: save, try, make live.

The easy way is the dashboard. Open Policies, then New version. Paste the policy. Use Check this request to try a few requests against it (the $40, $480 and $900 buttons fill in the refund cases). Press Save as new version. Then open the new version and press Make live.

Or use the API. These commands use jq to put the file into JSON.

Save it as a new version. It is checked, but it is not live yet:

bash
jq -n --rawfile source refunds.cedar '{source: $source, note: "Refunds, first version"}' \
  | curl -s -X POST "$RISKBOUND_URL/v1/policies" \
      -H "Authorization: Bearer $RISKBOUND_ADMIN_KEY" \
      -H "Content-Type: application/json" \
      -d @-

The answer includes "version":1. Now try a $480 refund against it. This records nothing:

bash
jq -n --rawfile source refunds.cedar \
  '{source: $source, agent: "support-bot", tool: "refund", params: {amount_minor: 48000, currency: "USD"}}' \
  | curl -s -X POST "$RISKBOUND_URL/v1/policies/simulate" \
      -H "Authorization: Bearer $RISKBOUND_ADMIN_KEY" \
      -H "Content-Type: application/json" \
      -d @-
json
{"draft":{"outcome":"ask_human","reasons":["refund-needs-approval"]},"live":null}

draft is what this file would decide. live is what the live policy decides today. It is null because nothing is live yet. Make version 1 live. Your name is recorded with the change:

bash
curl -s -X POST "$RISKBOUND_URL/v1/policies/1/activate" \
  -H "Authorization: Bearer $RISKBOUND_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{"actor": "Your name"}'

With no live policy, every action is blocked with the reason no_active_policy.

Step 4. Wrap the action with guard()#

guard() takes a tool name and your agent's name. It gives you back a function. Call that function with the params and the action. The SDK asks Riskbound first, then carries out the answer:

AnswerWhat the SDK does
allowRuns the action and reports that it ran
ask_humanWaits for a person. Runs the action if they approve. Throws if they reject, or nobody answers in time
dry_runRuns your dry-run handler, never the real action. Throws if you gave none
blockThrows a blocked error with the reasons. The action does not run

The SDK never decides by itself. If it cannot reach Riskbound, the action does not run (see page 7).

The SDKs are not on npm or PyPI yet. We share the code with you, and you install it from that folder.

TypeScript#

Build the SDK package once, from the shared code:

bash
cd /path/to/riskbound/sdk
npm install
npm run build
npm pack

This makes riskbound-sdk-0.1.0.tgz. To try it in a new folder:

bash
mkdir riskbound-try && cd riskbound-try
npm init -y
npm pkg set type=module
npm install /path/to/riskbound/sdk/riskbound-sdk-0.1.0.tgz

Save this as refund.ts:

ts
import { createRiskbound, RiskboundBlockedError } from "@riskbound/sdk";

const riskbound = createRiskbound({
  apiKey: process.env.RISKBOUND_API_KEY!,
  baseUrl: process.env.RISKBOUND_URL ?? "http://localhost:8200",
  approval: { pollIntervalMs: 1000, timeoutMs: 5 * 60_000 },
});

// One guard per sensitive action. "refund" is the tool name the policy sees.
const refund = riskbound.guard("refund", { agent: "support-bot" });

// Stands in for your real payments call.
async function issueRefund(orderId: string, amountMinor: number) {
  return `refunded ${amountMinor} cents on ${orderId}`;
}

async function tryRefund(orderId: string, amountMinor: number) {
  try {
    const result = await refund(
      { order_id: orderId, amount_minor: amountMinor, currency: "USD" },
      () => issueRefund(orderId, amountMinor),
    );
    console.log(orderId, result.outcome, "->", result.value);
  } catch (err) {
    if (err instanceof RiskboundBlockedError) {
      console.log(orderId, "blocked:", err.reasons.join(", "));
    } else {
      throw err;
    }
  }
}

await tryRefund("ord_1001", 4_000); // $40: allow
await tryRefund("ord_1002", 90_000); // $900: block
console.log("ord_1003 is waiting for a person. Approve it in the dashboard.");
await tryRefund("ord_1003", 48_000); // $480: ask a human

Run it. Node 22.18 and later run TypeScript files directly:

bash
node refund.ts

You will see:

ord_1001 allow -> refunded 4000 cents on ord_1001
ord_1002 blocked: refund-hard-cap
ord_1003 is waiting for a person. Approve it in the dashboard.

The script now waits. Go to step 5 and approve it. Then you will see:

ord_1003 ask_human -> refunded 48000 cents on ord_1003

In your real code, the action is your real call, for example () => payments.refund(orderId, amountMinor). If it throws, the SDK reports the action as failed and throws the same error again.

Python#

Install the SDK from the shared code, into your virtual environment:

bash
python3 -m venv .venv
.venv/bin/pip install /path/to/riskbound/sdk-python

Save this as refund.py:

python
import os

from riskbound import Riskbound, RiskboundBlockedError

rb = Riskbound(
    api_key=os.environ["RISKBOUND_API_KEY"],
    base_url=os.environ.get("RISKBOUND_URL", "http://localhost:8200"),
    approval_poll_interval=1.0,
    approval_timeout=300.0,
)

# One guard per sensitive action. "refund" is the tool name the policy sees.
refund = rb.guard("refund", agent="support-bot")


# Stands in for your real payments call.
def issue_refund(order_id, amount_minor):
    return f"refunded {amount_minor} cents on {order_id}"


def try_refund(order_id, amount_minor):
    try:
        result = refund(
            {"order_id": order_id, "amount_minor": amount_minor, "currency": "USD"},
            lambda: issue_refund(order_id, amount_minor),
        )
        print(order_id, result.outcome, "->", result.value)
    except RiskboundBlockedError as err:
        print(order_id, "blocked:", ", ".join(err.reasons))


try_refund("ord_2001", 4_000)  # $40: allow
try_refund("ord_2002", 90_000)  # $900: block
print("ord_2003 is waiting for a person. Approve it in the dashboard.")
try_refund("ord_2003", 48_000)  # $480: ask a human

Run it:

bash
.venv/bin/python refund.py

The output matches the TypeScript one. If you reject the request in step 5 instead of approving it, you will see ord_2003 blocked: approval_rejected.

For asyncio code, use AsyncRiskbound. The action can be an async function or a plain one:

python
import asyncio
import os

from riskbound import AsyncRiskbound


async def issue_refund():
    return "refunded"


async def main():
    rb = AsyncRiskbound(
        api_key=os.environ["RISKBOUND_API_KEY"],
        base_url=os.environ.get("RISKBOUND_URL", "http://localhost:8200"),
    )
    refund = rb.guard("refund", agent="support-bot")
    result = await refund(
        {"order_id": "ord_2004", "amount_minor": 2_500, "currency": "USD"},
        issue_refund,
    )
    print(result.outcome, result.value)


asyncio.run(main())

What the call gives back#

When the action ran, you get a result:

TypeScriptPythonMeaning
result.ranresult.rantrue if the real action ran
result.outcomeresult.outcomeallow, ask_human, dry_run, or fail_open (page 7)
result.decisionIdresult.decision_idThe decision's id in the log
result.valueresult.valueWhat your action returned

When it did not run, the SDK throws. The error names are the same in both languages:

ErrorWhenThe action ran?
RiskboundBlockedErrorPolicy, a limit, a stop or a person said no. reasons says whyNo
RiskboundApprovalTimeoutErrorNobody answered the approval in timeNo
RiskboundUnavailableErrorRiskbound could not be reachedNo
RiskboundRequestErrorThe request is wrong, for example a bad key or a fraction in an amountNo

Step 5. See allow, ask and block in the dashboard#

Sign in to the dashboard with your admin key and your name. Your name is recorded with every approval and every stop you make.

On your laptop: run the dashboard with the steps in dashboard/README.md. It opens on http://localhost:3210.

  1. Open Approvals. The $480 refund is waiting, with its params and the rule that asked for a person. Add a note and press Approve. Your script finishes.
  2. Open Decisions. You will see one row per request: allow for $40, block with refund-hard-cap for $900, and ask_human for $480. Use the outcome filter to see one kind at a time.
  3. Open Overview for the last 24 hours by outcome, and Watch for your agent, its tools and its risk score.

Page 5 has more on approvals, including Slack.

Next steps#

  • Send only the params your rules need (page 2).
  • Wrap your other sensitive actions, one guard each.
  • Read 7. Going to production before real traffic.
  • Optional: dry runs. Pass a dryRun handler (TypeScript) or dry_run= (Python) and write a policy with Action::"dry_run". The SDK READMEs in sdk/ and sdk-python/ have the details.