Hand work to a sub-agent
An agent passes part of a task to another agent, with fewer scopes, and the token records the whole chain.
What it shows
- A person allows the scopes
calendar:readandcalendar:write. The parent agent, "Meeting planner", exchanges the token of the person for a token in which it acts for that person. - The sub-agent, "Room finder", gets its own token and gives it to the parent.
- The parent exchanges its token again, with the token of the sub-agent as actor, and asks only for
calendar:read. - The token of the sub-agent names the person as subject. Its
actclaim holds the sub-agent, and inside it the parent. - LumoAuth refuses a scope that the sub-agent may not hold, and a scope that the parent does not hold.
Each step can only narrow the rights. The sub-agent never gets more than the parent holds, and never more than its own capabilities.
Before you start
- The application and the scopes of Act for a person, with consent. Its setup script creates them.
- Two agents with the switch May act on behalf of users. LumoAuth checks the switch for every agent in a chain. The setup script below registers "Meeting planner" with
calendar:readandcalendar:write, and "Room finder" withcalendar:readandcontacts:read. - Check that your plan includes acting for users in the plans matrix.
| 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 scripts only: an API key with the scopes admin:agents:read and admin:agents:write, and for the setup of the application also admin:permissions:read, admin:permissions:write, admin:clients:read and admin:clients:write. The agents do not read it. |
LUMOAUTH_CLIENT_ID | For signin.mjs: the client ID of the application "Acme Calendar". The first setup script prints it. |
AGENT_CLIENT_ID | The client ID of the parent agent, "Meeting planner". The setup script prints it. |
AGENT_CLIENT_SECRET | The client secret of the parent agent. The setup script prints it. |
SUB_AGENT_CLIENT_ID | The client ID of the sub-agent, "Room finder". The setup script prints it. |
SUB_AGENT_CLIENT_SECRET | The client secret of the sub-agent. The setup script prints it. |
USER_ACCESS_TOKEN | The access token of the person, with the scopes calendar:read and calendar:write. signin.mjs prints it. |
The first script creates the scopes and the application of the recipe for acting for a person. The second one, shown here, registers the two agents. Then signin.mjs signs the person in: open http://localhost:3000 and sign in. Use AGENT_CLIENT_ID and AGENT_CLIENT_SECRET of the second script.
node delegation/act-for-a-user/setup.mjs
node delegation/sub-agents/setup.mjs
node delegation/act-for-a-user/signin.mjs
setup.mjs
// Registers the two agents of the recipe: a parent agent that may read and
// write a calendar, and a sub-agent that may only read it. Both may act for
// people. Run it again at any time.
//
// node delegation/sub-agents/setup.mjs
//
// The API key needs the scopes admin:agents:read and admin:agents:write.
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
async function agent(name, description, capabilities) {
const found = await ensure('/admin/agents', (a) => a.name === name, {
name,
description,
identityType: 'client_secret',
capabilities,
// The switch "May act on behalf of users" of the portal. LumoAuth checks
// it for every agent in a chain, also for the sub-agent.
canActOnBehalfOfUsers: true,
});
// LumoAuth shows a secret once. A second run therefore asks for a new
// secret, and the old one stops.
const secret =
found.clientSecret ??
(await call('POST', `/admin/agents/${found.agentId}/rotate-credentials`)).data.clientSecret;
return { id: found.agentId, secret };
}
const planner = await agent('Meeting planner', 'Plans meetings for a person, and hands parts of the work to other agents.', [
'calendar:read',
'calendar:write',
]);
const finder = await agent('Room finder', 'Looks for free time and free rooms. It never changes a calendar.', [
'calendar:read',
'contacts:read',
]);
console.log('The agents "Meeting planner" and "Room finder" are ready.');
printEnv({
AGENT_CLIENT_ID: planner.id,
AGENT_CLIENT_SECRET: planner.secret,
SUB_AGENT_CLIENT_ID: finder.id,
SUB_AGENT_CLIENT_SECRET: finder.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. Each program was run with the token of a person who signed in through signin.mjs.
- Node.js
- Python
- Go
- Java
- C#
// A parent agent acts for a person, and hands part of the work to a
// sub-agent with fewer rights. The token of the sub-agent records the chain.
//
// node delegation/sub-agents/js/delegate.mjs
import { DelegationModule } from '@lumoauth/backend';
import { LumoAgent } from '@lumoauth/agent';
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const planner = new LumoAgent();
const finder = new LumoAgent({
clientId: process.env.SUB_AGENT_CLIENT_ID,
clientSecret: process.env.SUB_AGENT_CLIENT_SECRET,
});
// The parent acts for the person, with both scopes that the person allowed.
planner.delegation.setUserToken('jordan', process.env.USER_ACCESS_TOKEN);
await planner.delegation.exchange('jordan', ['calendar:read', 'calendar:write']);
// The sub-agent sends its own token to the parent. The parent passes on
// only the scope that the work needs.
const finderToken = await finder.getAccessToken();
const token = await planner.delegation.delegateToSubAgent('jordan', finderToken, ['calendar:read']);
console.log(`subject: ${DelegationModule.getSubject(token)} (the person)`);
// The actors, from the agent that acts now back to the first one.
console.log(`chain: ${DelegationModule.parseActorChain(token).join(', ')}`);
// More than the sub-agent may do, or more than the parent holds: LumoAuth refuses.
for (const scope of ['calendar:write', 'contacts:read']) {
try {
await planner.delegation.delegateToSubAgent('jordan', finderToken, [scope]);
console.log(`${scope} for the sub-agent: granted`);
} catch (error) {
console.log(`${scope} for the sub-agent: refused (${error.code})`);
}
}
node delegation/sub-agents/js/delegate.mjs
"""A parent agent acts for a person, and hands part of the work to a
sub-agent with fewer rights. The token of the sub-agent records the chain.
python delegation/sub-agents/python/delegate.py
"""
import os
from lumoauth import DelegationChain, LumoAuthAgent, LumoAuthApiError
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
planner = LumoAuthAgent()
finder = LumoAuthAgent(
client_id=os.environ["SUB_AGENT_CLIENT_ID"],
client_secret=os.environ["SUB_AGENT_CLIENT_SECRET"],
)
if not planner.authenticate() or not finder.authenticate():
raise SystemExit("An agent could not authenticate. Check its ID and its secret.")
# The parent acts for the person, with both scopes that the person allowed.
chain = DelegationChain(planner)
chain.set_user_token("jordan", os.environ["USER_ACCESS_TOKEN"])
chain.exchange("jordan", ["calendar:read", "calendar:write"])
# The sub-agent sends its own token to the parent. The parent passes on
# only the scope that the work needs.
finder_token = finder.access_token
token = chain.delegate_to_sub_agent("jordan", finder_token, ["calendar:read"])
print(f"subject: {DelegationChain.get_subject(token)} (the person)")
# The actors, from the agent that acts now back to the first one.
print(f"chain: {', '.join(DelegationChain.parse_actor_chain(token))}")
# More than the sub-agent may do, or more than the parent holds: LumoAuth refuses.
for scope in ["calendar:write", "contacts:read"]:
try:
chain.delegate_to_sub_agent("jordan", finder_token, [scope])
print(f"{scope} for the sub-agent: granted")
except LumoAuthApiError as error:
print(f"{scope} for the sub-agent: refused ({error.code})")
python delegation/sub-agents/python/delegate.py
// A parent agent acts for a person, and hands part of the work to a
// sub-agent with fewer rights. The token of the sub-agent records the chain.
//
// go run ./delegation/sub-agents/go
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
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.
planner, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
finder, err := lumoauth.NewAgent(lumoauth.AgentConfig{
ClientID: os.Getenv("SUB_AGENT_CLIENT_ID"),
ClientSecret: os.Getenv("SUB_AGENT_CLIENT_SECRET"),
})
if err != nil {
log.Fatal(err)
}
// The parent acts for the person, with both scopes that the person allowed.
chain := lumoauth.NewDelegationChain(planner, "")
if err := chain.SetUserToken("jordan", os.Getenv("USER_ACCESS_TOKEN")); err != nil {
log.Fatal(err)
}
if _, err := chain.Exchange(ctx, "jordan", "calendar:read", "calendar:write"); err != nil {
log.Fatal(err)
}
// The sub-agent sends its own token to the parent. The parent passes on
// only the scope that the work needs.
finderToken, err := finder.AccessToken(ctx)
if err != nil {
log.Fatal(err)
}
token, err := chain.DelegateToSubAgent(ctx, "jordan", finderToken, "calendar:read")
if err != nil {
log.Fatal(err)
}
subject, err := lumoauth.TokenSubject(token)
if err != nil {
log.Fatal(err)
}
actors, err := chain.ActorChain(token)
if err != nil {
log.Fatal(err)
}
fmt.Printf("subject: %s (the person)\n", subject)
// The actors, from the agent that acts now back to the first one.
fmt.Printf("chain: %s\n", strings.Join(actors, ", "))
// More than the sub-agent may do, or more than the parent holds: LumoAuth refuses.
for _, scope := range []string{"calendar:write", "contacts:read"} {
_, err := chain.DelegateToSubAgent(ctx, "jordan", finderToken, scope)
if apiErr, ok := lumoauth.AsAPIError(err); ok {
fmt.Printf("%s for the sub-agent: refused (%s)\n", scope, apiErr.Code)
} else if err != nil {
log.Fatal(err)
} else {
fmt.Printf("%s for the sub-agent: granted\n", scope)
}
}
}
go run ./delegation/sub-agents/go
// A parent agent acts for a person, and hands part of the work to a
// sub-agent with fewer rights. The token of the sub-agent records the chain.
//
// java -cp "java/lib/*" delegation/sub-agents/java/Delegate.java
import io.lumoauth.DelegationChain;
import io.lumoauth.LumoAgent;
import io.lumoauth.errors.LumoAuthApiException;
import io.lumoauth.resources.DelegationResource;
import java.util.List;
public class Delegate {
public static void main(String[] args) {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
LumoAgent planner = LumoAgent.fromEnvironment();
LumoAgent finder = LumoAgent.builder()
.clientId(System.getenv("SUB_AGENT_CLIENT_ID"))
.clientSecret(System.getenv("SUB_AGENT_CLIENT_SECRET"))
.build();
// The parent acts for the person, with both scopes that the person allowed.
DelegationChain chain = new DelegationChain(planner, null);
chain.setUserToken("jordan", System.getenv("USER_ACCESS_TOKEN"));
chain.exchange("jordan", "calendar:read", "calendar:write");
// The sub-agent sends its own token to the parent. The parent passes on
// only the scope that the work needs.
String finderToken = finder.accessToken();
String token = chain.delegateToSubAgent("jordan", finderToken, "calendar:read");
System.out.printf("subject: %s (the person)%n", DelegationResource.tokenSubject(token).orElseThrow());
// The actors, from the agent that acts now back to the first one.
System.out.printf("chain: %s%n", String.join(", ", chain.actorChain(token)));
// More than the sub-agent may do, or more than the parent holds: LumoAuth refuses.
for (String scope : List.of("calendar:write", "contacts:read")) {
try {
chain.delegateToSubAgent("jordan", finderToken, scope);
System.out.printf("%s for the sub-agent: granted%n", scope);
} catch (LumoAuthApiException error) {
System.out.printf("%s for the sub-agent: refused (%s)%n", scope, error.code());
}
}
}
}
java -cp "java/lib/*" delegation/sub-agents/java/Delegate.java
#:package LumoAuth@1.7.0
#:property PublishAot=false
// A parent agent acts for a person, and hands part of the work to a
// sub-agent with fewer rights. The token of the sub-agent records the chain.
//
// dotnet run delegation/sub-agents/csharp/Delegate.cs
using LumoAuth;
using LumoAuth.Errors;
using LumoAuth.Resources;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
using var planner = LumoAgent.FromEnvironment();
using var finder = new LumoAgent(new LumoAgentOptions
{
ClientId = Environment.GetEnvironmentVariable("SUB_AGENT_CLIENT_ID"),
ClientSecret = Environment.GetEnvironmentVariable("SUB_AGENT_CLIENT_SECRET"),
});
// The parent acts for the person, with both scopes that the person allowed.
var chain = new DelegationChain(planner, "");
chain.SetUserToken("jordan", Environment.GetEnvironmentVariable("USER_ACCESS_TOKEN")!);
await chain.ExchangeAsync("jordan", ["calendar:read", "calendar:write"]);
// The sub-agent sends its own token to the parent. The parent passes on
// only the scope that the work needs.
var finderToken = await finder.GetAccessTokenAsync();
var token = await chain.DelegateToSubAgentAsync("jordan", finderToken, ["calendar:read"]);
Console.WriteLine($"subject: {DelegationResource.TokenSubject(token)} (the person)");
// The actors, from the agent that acts now back to the first one.
Console.WriteLine($"chain: {string.Join(", ", DelegationChain.ActorChain(token))}");
// More than the sub-agent may do, or more than the parent holds: LumoAuth refuses.
foreach (var scope in new[] { "calendar:write", "contacts:read" })
{
try
{
await chain.DelegateToSubAgentAsync("jordan", finderToken, [scope]);
Console.WriteLine($"{scope} for the sub-agent: granted");
}
catch (LumoAuthApiException error)
{
Console.WriteLine($"{scope} for the sub-agent: refused ({error.Code})");
}
}
dotnet run delegation/sub-agents/csharp/Delegate.cs
The program holds the secrets of both agents, so that it can show both sides in one run. In a real system the sub-agent runs on its own and sends only its access token to the parent. In an agent framework such as CrewAI or LangGraph, make the second exchange where the parent hands a task to the other agent.
Check the result
subject: 01a21fe8-6814-7111-ba52-084c43664ec5 (the person)
chain: agent_agt_3f010c5aa2fc5f54, agent_agt_6c9d5d39d7003882
calendar:write for the sub-agent: refused (invalid_scope)
contacts:read for the sub-agent: refused (invalid_scope)
- The chain lists the actors from the agent that acts now back to the first one: Room finder, then Meeting planner.
calendar:writeis refused because "Room finder" may only read.contacts:readis refused because the parent does not hold it, although the sub-agent may.- Open Audit logs under Security in the portal. Each exchange adds an event
oauth.token_exchange, with the acting agent as actor and the person as target.
Limits
- A chain holds at most 5 actors. An exchange that would make it deeper fails with
invalid_requestand "Delegation chain too deep". - The token of the sub-agent expires no later than the token of the parent.
- The token of a parent can be passed on only while its audience is the parent itself. A token that names another API with
resourcecannot become the subject of a further exchange. - The programs read the token without a check of its signature. Your API verifies the token before it trusts the chain: see Verify access tokens.