# Gate a tool call

Give your agent a spending rule, let a small purchase through, send a larger one to a person, approve it, and run the tool once it's approved.

In this quickstart your agent orders office supplies. You set a rule that a person approves anything over 100, let a small order through, send a larger one for approval, approve it, and run the tool. You use curl with `jq`, or Node, or Python, and a published sandbox key, so you don't need an account.

### 1. Set your key and a rule

The sandbox account key has the `mandate` scope. Every key is listed on [Sandbox and keys](https://provenanceauth.com/docs/get-started/sandbox.md). Save a [policy](https://provenanceauth.com/docs/concepts/policies.md) with one rule with [`PUT /v1/mandate/policies`](https://provenanceauth.com/docs/api/policies.md#put-v1-mandate-policies): an amount over 100 needs a person's approval.

**curl**

```bash
export PROVENANCE_API=https://sandbox-api.provenanceauth.com
export PROVENANCE_KEY=prv_test_acct_P9xN2vQ7bT4mW8sYd3cFjLh6gAe1kR5

curl -s -X PUT $PROVENANCE_API/v1/mandate/policies \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "note": "a person approves orders over 100",
    "document": { "rules": [
      { "id": "ask-above-100", "when": [{ "fact": "transaction_amount", "op": "gt", "value": 100 }], "require": { "approval": true } }
    ] }
  }'
```

**Node**

```ts
import { Provenance } from "@provenanceauth/sdk";

const prov = new Provenance({ apiKey: process.env.PROVENANCE_KEY!, baseUrl: process.env.PROVENANCE_API });
await prov.mandate.policies.set(
  { rules: [{ id: "ask-above-100", when: [{ fact: "transaction_amount", op: "gt", value: 100 }], require: { approval: true } }] },
  { note: "a person approves orders over 100" },
);
```

**Python**

```python
import os
from provenanceauth import Provenance

prov = Provenance(os.environ["PROVENANCE_KEY"], base_url=os.environ["PROVENANCE_API"])
prov.mandate.policies.set(
    {"rules": [{"id": "ask-above-100", "when": [{"fact": "transaction_amount", "op": "gt", "value": 100}], "require": {"approval": True}}]},
    note="a person approves orders over 100",
)
```

```json
{
  "object": "policy_version",
  "domain": "intent",
  "active": true,
  "note": "a person approves orders over 100"
}
```

The rule reads `transaction_amount` from the `context` your agent sends with each decision.

### 2. Let a small order through

Before the tool runs, the agent describes the call and binds its exact input: [`POST /v1/mandate/intents`](https://provenanceauth.com/docs/api/intent-tokens.md#post-v1-mandate-intents) returns an intent token, and [`POST /v1/mandate/assessments`](https://provenanceauth.com/docs/api/intent-tokens.md#post-v1-mandate-assessments) decides it. In Node and Python, `gate()` and `decide_tool_call` make both calls for you, so this is the one call your agent makes.

**curl**

```bash
curl -s $PROVENANCE_API/v1/mandate/intents \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "action_description": "Order printer paper from Brindlecote Office: 40.00 USD",
    "action_payload": { "tool": "order_supplies", "sku": "paper-a4-5", "amount": 40, "currency": "USD" },
    "agent_session_id": "sess_quickstart_1",
    "device_id": "dev_00000000000000000000000000000001"
  }' > small.json

curl -s $PROVENANCE_API/v1/mandate/assessments \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "intent_token": "'"$(jq -r .intent_token small.json)"'",
    "action_description": "Order printer paper from Brindlecote Office: 40.00 USD",
    "action_payload": { "tool": "order_supplies", "sku": "paper-a4-5", "amount": 40, "currency": "USD" },
    "context": { "transaction_amount": 40 }
  }'
```

**Node**

```ts
import { gate } from "@provenanceauth/agent-adapters";

async function orderSupplies(args: { sku: string; amount: number; currency: string }) {
  return { ordered: args.sku };
}

const gatedOrder = gate(orderSupplies, {
  client: prov,
  deviceId: "dev_00000000000000000000000000000001",
  agentSessionId: "sess_quickstart_1",
  describe: (a) => `Order printer paper from Brindlecote Office: ${a.amount}.00 ${a.currency}`,
  payload: (a) => ({ tool: "order_supplies", ...a }),
  context: (a) => ({ transaction_amount: a.amount }),
});

console.log(await gatedOrder({ sku: "paper-a4-5", amount: 40, currency: "USD" })); // { ordered: "paper-a4-5" }
```

**Python**

```python
from provenanceauth.gate import decide_tool_call

def order_supplies(args):
    return {"ordered": args["sku"]}

options = dict(
    client=prov,
    device_id="dev_00000000000000000000000000000001",
    agent_session_id="sess_quickstart_1",
    describe=lambda a: f"Order printer paper from Brindlecote Office: {a['amount']}.00 {a['currency']}",
    payload=lambda a: {"tool": "order_supplies", **a},
    context=lambda a: {"transaction_amount": a["amount"]},
    timeout_ms=0,
)
small = {"sku": "paper-a4-5", "amount": 40, "currency": "USD"}
decision = decide_tool_call("order_supplies", small, **options)
if decision.allowed:
    print(order_supplies(small))
```

```json
{
  "object": "mandate_assessment",
  "valid": true,
  "payload_bound": true
}
```

The order is under the rule, so the decision is valid and the tool runs. `payload_bound: true` means the input that runs is the input that was decided.

### 3. Send a larger order to a person

The same call for 240 matches the rule. The decision is `approval_pending`, with the approval's id, and the request goes to the person.

**curl**

```bash
curl -s $PROVENANCE_API/v1/mandate/intents \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "action_description": "Order a label printer from Brindlecote Office: 240.00 USD",
    "action_payload": { "tool": "order_supplies", "sku": "printer-label-2", "amount": 240, "currency": "USD" },
    "agent_session_id": "sess_quickstart_1",
    "device_id": "dev_00000000000000000000000000000001"
  }' > large.json

curl -s $PROVENANCE_API/v1/mandate/assessments \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "intent_token": "'"$(jq -r .intent_token large.json)"'",
    "action_description": "Order a label printer from Brindlecote Office: 240.00 USD",
    "action_payload": { "tool": "order_supplies", "sku": "printer-label-2", "amount": 240, "currency": "USD" },
    "context": { "transaction_amount": 240 }
  }' | tee decision.json
```

**Node**

```ts
import { IntentDeniedError } from "@provenanceauth/agent-adapters";

const large = { sku: "printer-label-2", amount: 240, currency: "USD" };
let approvalId: string | undefined;
try {
  await gatedOrder(large);
} catch (err) {
  if (err instanceof IntentDeniedError && err.pending) approvalId = err.approvalId; // tell the person what you're waiting for
  else throw err;
}
```

**Python**

```python
large = {"sku": "printer-label-2", "amount": 240, "currency": "USD"}
decision = decide_tool_call("order_supplies", large, **options)
print(decision.pending, decision.approval_id)  # True appr_…
```

```json
{
  "object": "mandate_assessment",
  "valid": false,
  "reason": "approval_pending",
  "policy": {
    "id": "pol_3F9A1C7E52B04D8E6A1F27C9B4",
    "version": 1,
    "rule": {
      "id": "rul_01JDCBCHZ4Y3ZN99AFPMHJCAGY",
      "name": null,
      "phase": "assess",
      "action": "challenge",
      "conditions": [
        { "fact": "transaction_amount", "op": "gt", "value": 100, "actual": 240 }
      ]
    }
  }
}
```

Don't run the tool yet. The approval waits 10 minutes for an answer.

```bash
export APPROVAL_ID=$(jq -r .approval_id decision.json)
```

### 4. Approve the request

A real person approves on their phone, from the link Provenance sends, or in the console's **Approvals** inbox. In the sandbox you approve it with the key through [`POST /v1/mandate/approvals/{id}/respond`](https://provenanceauth.com/docs/api/approvals.md#post-v1-mandate-approvals-id-respond).

**curl**

```bash
curl -s $PROVENANCE_API/v1/mandate/approvals/$APPROVAL_ID/respond \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "decision": "approve" }'
```

**Node**

```ts
await prov.mandate.approvals.respond(approvalId!, { decision: "approve" });
```

**Python**

```python
prov.mandate.approvals.respond(decision.approval_id, decision="approve")
```

```json
{
  "object": "approval",
  "status": "approved",
  "matched_rule_id": "rul_01JDCBCHZ4Y3ZN99AFPMHJCAGY",
  "decided_via": "api",
  "decided_method": "api_key"
}
```

### 5. Decide again and run the tool

The agent repeats the same decision with the same token. The approval satisfies the rule, so the decision is valid and names the approval.

**curl**

```bash
curl -s $PROVENANCE_API/v1/mandate/assessments \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "intent_token": "'"$(jq -r .intent_token large.json)"'",
    "action_description": "Order a label printer from Brindlecote Office: 240.00 USD",
    "action_payload": { "tool": "order_supplies", "sku": "printer-label-2", "amount": 240, "currency": "USD" },
    "context": { "transaction_amount": 240 }
  }'
```

**Node**

```ts
// The same arguments reuse the pending token, so the call now goes through.
console.log(await gatedOrder(large)); // { ordered: "printer-label-2" }
```

**Python**

```python
decision = decide_tool_call("order_supplies", large, **options)
if decision.allowed:
    print(order_supplies(large))
```

```json
{
  "object": "mandate_assessment",
  "valid": true,
  "payload_bound": true
}
```

Every decision, the approval and who gave it are in the [decision ledger](https://provenanceauth.com/docs/mandate/concepts/decision-ledger.md), hash-chained and exportable.

## Try it

The [Mandate explorer](https://provenanceauth.com/mandate#endpoints) runs these calls in your browser. When you're done, put the sandbox account back on the default policy with [`DELETE /v1/mandate/policies`](https://provenanceauth.com/docs/api/policies.md#delete-v1-mandate-policies):

**curl**

```bash
curl -s -X DELETE $PROVENANCE_API/v1/mandate/policies \
  -H "Authorization: Bearer $PROVENANCE_KEY"
```

**Node**

```ts
await prov.mandate.policies.reset();
```

**Python**

```python
prov.mandate.policies.reset()
```

```json
{
  "object": "policy",
  "domain": "intent",
  "is_default": true
}
```

## Next steps

- [Set limits and policy](https://provenanceauth.com/docs/mandate/guides/set-limits-and-policy.md): counterparties, budgets, grants with an end date and simulate before you activate.
- [Framework integrations](https://provenanceauth.com/docs/mandate/guides/framework-integrations.md): gate tools in the AI SDK, LangChain, the OpenAI Agents SDK and more.
- [Step-up approval](https://provenanceauth.com/docs/mandate/guides/step-up-approval.md): who gets the request, on which channel, and how a decision is recorded.
- [Example apps](https://provenanceauth.com/docs/get-started/example-apps.md): small working apps that use this product end to end.
