Ask before acting
Before each action, the agent asks LumoAuth whether it may do it, and receives the answer with the reason.
What it shows
- An agent, "Billing assistant", holds one capability:
invoices:read. - Before it reads an invoice, the agent asks LumoAuth. The answer is yes.
- Before it refunds the same invoice, it asks again. The answer is no.
- Each answer carries a reason and the name of the check that decided:
capability,pdpordeny_override. - On a no, the agent stops and can show the reason to the person.
The agent sends the action and a context: the invoice and the amount. Your attribute rules can read that context.
Before you start
- An agent in the registry with the capability
invoices:read, and its client ID and secret. The setup script registers the agent and prints both values. - The setup script needs an API key with the scopes
admin:agents:readandadmin:agents:write. Create it in the portal under Applications & developer tools, API keys.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | For the setup script only: an API key with the scopes admin:agents:read and admin:agents:write. |
AGENT_CLIENT_ID | The client ID of the agent. The setup script prints it. |
AGENT_CLIENT_SECRET | The client secret of the agent. The setup script prints it once. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node agents/ask-before-acting/setup.mjs
setup.mjs
// Registers the agent of the recipe, "Billing assistant", with one capability,
// and prints its client ID and secret. Run it again at any time.
//
// node agents/ask-before-acting/setup.mjs
//
// The API key needs the scopes admin:agents:read and admin:agents:write.
import { call, list, printEnv } from '../../_lib/admin.mjs';
const name = 'Billing assistant';
const capabilities = ['invoices:read'];
let agent = (await list('/admin/agents')).find((a) => a.name === name);
let secret;
if (agent) {
// LumoAuth shows a secret once. A second run therefore makes a new secret,
// and the old one stops working.
await call('PUT', `/admin/agents/${agent.agentId}/scopes`, { scopes: capabilities });
secret = (await call('POST', `/admin/agents/${agent.agentId}/rotate-credentials`)).data.clientSecret;
} else {
agent = (
await call('POST', '/admin/agents', {
name,
description: 'Reads invoices. It may not refund them.',
identityType: 'client_secret',
capabilities,
})
).data;
secret = agent.clientSecret;
}
console.log(`Agent "${name}" (${agent.agentId}) holds: ${capabilities.join(', ')}`);
printEnv({ AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: secret });
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. The curl version prints the two answers as JSON.
- Node.js
- Python
- Go
- Java
- C#
- curl
agents/ask-before-acting/js/ask.mjs
// Before each action, the agent asks LumoAuth whether it may do it.
//
// node agents/ask-before-acting/js/ask.mjs
import { LumoAgent } from '@lumoauth/agent';
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();
const invoice = { invoice: 'INV-7741', amount: 120 };
for (const action of ['invoices:read', 'invoices:refund']) {
// The context describes this one action. LumoAuth passes it to your rules.
const answer = await agent.ask(action, invoice);
console.log(`${action}: ${answer.allowed ? 'allowed' : 'denied'}, decided by ${answer.decided_by}`);
console.log(` reason: ${answer.reason}`);
if (!answer.allowed) {
// The agent stops here. It can show the reason to the person.
console.log(` audit ID: ${answer.audit_id}`);
}
}
node agents/ask-before-acting/js/ask.mjs
agents/ask-before-acting/python/ask.py
# Before each action, the agent asks LumoAuth whether it may do it.
#
# python agents/ask-before-acting/python/ask.py
from lumoauth import LumoAuthAgent
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent = LumoAuthAgent()
invoice = {"invoice": "INV-7741", "amount": 120}
for action in ["invoices:read", "invoices:refund"]:
# The context describes this one action. LumoAuth passes it to your rules.
answer = agent.ask(action, context=invoice)
print(f"{action}: {'allowed' if answer['allowed'] else 'denied'}, decided by {answer['decided_by']}")
print(f" reason: {answer['reason']}")
if not answer["allowed"]:
# The agent stops here. It can show the reason to the person.
print(f" audit ID: {answer['audit_id']}")
python agents/ask-before-acting/python/ask.py
agents/ask-before-acting/go/main.go
// Before each action, the agent asks LumoAuth whether it may do it.
//
// go run ./agents/ask-before-acting/go
package main
import (
"context"
"fmt"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
ctx := context.Background()
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
invoice := map[string]any{"invoice": "INV-7741", "amount": 120}
for _, action := range []string{"invoices:read", "invoices:refund"} {
// The context describes this one action. LumoAuth passes it to your rules.
answer, err := agent.Ask(ctx, action, invoice)
if err != nil {
log.Fatal(err)
}
verdict := "denied"
if answer.Allowed {
verdict = "allowed"
}
// Raw holds every field of the answer, also the ones without a typed field.
fmt.Printf("%s: %s, decided by %v\n", action, verdict, answer.Raw["decided_by"])
fmt.Printf(" reason: %s\n", answer.Reason)
if !answer.Allowed {
// The agent stops here. It can show the reason to the person.
fmt.Printf(" audit ID: %s\n", answer.AuditID)
}
}
}
go run ./agents/ask-before-acting/go
agents/ask-before-acting/java/AskBeforeActing.java
// Before each action, the agent asks LumoAuth whether it may do it.
//
// java -cp "java/lib/*" agents/ask-before-acting/java/AskBeforeActing.java
import io.lumoauth.LumoAgent;
import io.lumoauth.model.AgentAskResult;
import java.util.List;
import java.util.Map;
public class AskBeforeActing {
public static void main(String[] args) {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
LumoAgent agent = LumoAgent.fromEnvironment();
Map<String, Object> invoice = Map.of("invoice", "INV-7741", "amount", 120);
for (String action : List.of("invoices:read", "invoices:refund")) {
// The context describes this one action. LumoAuth passes it to your rules.
AgentAskResult answer = agent.ask(action, invoice);
// raw() holds every field of the answer, also the ones without a typed field.
System.out.printf("%s: %s, decided by %s%n",
action, answer.allowed() ? "allowed" : "denied", answer.raw().get("decided_by"));
System.out.printf(" reason: %s%n", answer.reason());
if (!answer.allowed()) {
// The agent stops here. It can show the reason to the person.
System.out.printf(" audit ID: %s%n", answer.auditId());
}
}
}
}
java -cp "java/lib/*" agents/ask-before-acting/java/AskBeforeActing.java
agents/ask-before-acting/csharp/AskBeforeActing.cs
#:package LumoAuth@1.7.0
#:property PublishAot=false
// Before each action, the agent asks LumoAuth whether it may do it.
//
// dotnet run agents/ask-before-acting/csharp/AskBeforeActing.cs
using LumoAuth;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
var agent = LumoAgent.FromEnvironment();
var invoice = new Dictionary<string, object> { ["invoice"] = "INV-7741", ["amount"] = 120 };
foreach (var action in new[] { "invoices:read", "invoices:refund" })
{
// The context describes this one action. LumoAuth passes it to your rules.
var answer = await agent.AskAsync(action, invoice);
// Raw holds every field of the answer, also the ones without a typed property.
var decidedBy = answer.Raw.GetProperty("decided_by").GetString();
Console.WriteLine($"{action}: {(answer.Allowed ? "allowed" : "denied")}, decided by {decidedBy}");
Console.WriteLine($" reason: {answer.Reason}");
if (!answer.Allowed)
{
// The agent stops here. It can show the reason to the person.
Console.WriteLine($" audit ID: {answer.AuditId}");
}
}
dotnet run agents/ask-before-acting/csharp/AskBeforeActing.cs
agents/ask-before-acting/http/ask.sh
#!/bin/sh
# Before each action, the agent asks LumoAuth whether it may do it, with curl.
#
# sh agents/ask-before-acting/http/ask.sh
set -eu
API="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1"
# The agent gets its own access token with the client credentials grant.
TOKEN=$(curl --silent --show-error "$API/oauth/token" \
--user "$AGENT_CLIENT_ID:$AGENT_CLIENT_SECRET" \
--data "grant_type=client_credentials" |
sed -n 's/.*"access_token" *: *"\([^"]*\)".*/\1/p')
for ACTION in invoices:read invoices:refund; do
# The context describes this one action. LumoAuth passes it to your rules.
curl --silent --show-error "$API/agents/ask" \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/json" \
--data "{\"action\": \"$ACTION\", \"context\": {\"invoice\": \"INV-7741\", \"amount\": 120}}"
echo
done
sh agents/ask-before-acting/http/ask.sh
Check the result
Output
invoices:read: allowed, decided by capability
reason: Agent has authorized capability for 'invoices:read'.
invoices:refund: denied, decided by capability
reason: Agent lacks required capability for 'invoices:refund'.
audit ID: 2a36ff5b41052fed
- Open Audit logs in the portal and filter by the event type
agent.capability_check_denied. The refusal is there, with the agent as the actor. - Add
invoices:refundto the agent's capabilities and run the program again. Both answers are now "allowed". - The Test this agent section on the agent's page in the portal makes the same check.
Limits
- LumoAuth writes a refusal to the audit log. It does not write an allowed answer, because agents ask at every step.
- An agent writes the action with
:. An action with a., such asinvoices.refund, gets400 invalid_action. - Each question counts against the budget of the agent, when it has one.
- The number of questions for each month depends on the plan. Check that your plan includes the Ask API in the plans matrix.
- For a check without a network call, see Check capabilities without a network call.