Python API reference¶
Who this page is for: developers wiring Castellan into agent code. After reading it you will know which objects to import, how to authorize a call, and what each class and function promises. The text below is generated from the docstrings in the source, so it always matches the installed version.
The 30-second tour¶
Most programs use four things: a Guard, a Principal for each agent, ToolCall objects, and the Decision that comes back.
import secrets
from agent_castellan import Effect, Guard, ToolCall
guard = Guard.from_file("first-policy.yaml", key=secrets.token_bytes(32))
planner = guard.start_run("planner", on_behalf_of="alice")
decision = guard.authorize(planner, ToolCall(tool="fs.read", args={"path": "/workspace/app.py"}))
if decision.effect is Effect.ALLOW:
... # run the tool
The getting started page runs a complete version of this, including delegation and approvals, with its real output.
Everything in the first section below is importable straight from agent_castellan. The other modules are imported by path.
Guard¶
agent_castellan.Guard
¶
The single entry point: runs every tool call through the full authorization pipeline.
A guard wires together a policy, a grant verifier, an approval store, a budget tracker
and an audit log. Most users build one with Guard.from_file.
Example
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decider
|
PolicyDecider
|
Policy engine that answers allow, deny or ask. |
required |
grants
|
GrantVerifier
|
Verifier and minter for delegation grants. |
required |
approvals
|
ApprovalStore
|
Store of approval requests. |
required |
budgets
|
BudgetTracker
|
Tracker of run, role and grant limits. |
required |
audit
|
AuditSink
|
Sink that records every |
required |
clock
|
Clock
|
Source of the current time. |
required |
approval_ttl
|
int
|
Seconds an approval request stays valid. |
600
|
from_file(policy_path, *, key=None, state_path=None)
classmethod
¶
Build a guard with the real components from a policy file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy_path
|
str | Path
|
Path of the policy YAML file. |
required |
key
|
bytes | None
|
Root key (at least 32 bytes) used to sign grants. When omitted, the
hex-encoded |
None
|
state_path
|
str | Path | None
|
SQLite file for approvals and budgets. When omitted, both live in
memory and vanish when the process ends. Set it to share state between
processes, for example with |
None
|
Returns:
| Type | Description |
|---|---|
Guard
|
A fully wired guard. The audit log is written to the policy's |
Raises:
| Type | Description |
|---|---|
PolicyError
|
The policy file cannot be read or is invalid. |
GrantError
|
The key is shorter than 32 bytes or |
start_run(role, *, on_behalf_of=None)
¶
Create the root principal of a new run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role
|
str
|
Role of the root agent, for example |
required |
on_behalf_of
|
str | None
|
Id of the end user the run acts for; copied to every child. |
None
|
Returns:
| Type | Description |
|---|---|
Principal
|
A principal with depth 0 and a fresh |
delegate(parent, child_role, *, tools, when=None, ttl_seconds=900, max_calls=None)
¶
Create a child principal and the grant that bounds its power.
The child can never do more than the parent: tools must be covered by the
parent's own grant, and expiry and max_calls can only shrink.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent
|
Principal
|
The delegating agent. |
required |
child_role
|
str
|
Role of the new agent. |
required |
tools
|
Sequence[str]
|
Tool globs the child may use, for example |
required |
when
|
dict[str, Any] | None
|
Extra conditions in the rule |
None
|
ttl_seconds
|
int
|
Lifetime of the grant in seconds. A child grant may not outlive its parent's, so when you delegate again from a delegated agent, pass a value smaller than the time its own grant has left. |
900
|
max_calls
|
int | None
|
Optional cap on calls made under this grant. The value is stored
and signed in the grant, but the guard does not yet count calls against
it; use the policy |
None
|
Returns:
| Type | Description |
|---|---|
Principal
|
The child principal and its signed grant. Pass the grant (or the chain) |
Grant
|
to |
Raises:
| Type | Description |
|---|---|
PermissionDenied
|
The policy does not let |
GrantError
|
The request would widen the parent's power. |
authorize(principal, call, *, chain=())
¶
Decide one call, record it, and count it if it was allowed.
The pipeline is: budget precheck, policy decision, grant chain check, approval, audit append, then budget consume (only when the final answer is allow).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
principal
|
Principal
|
The agent making the call. |
required |
call
|
ToolCall
|
The tool call to authorize. |
required |
chain
|
Sequence[Grant]
|
Grants from the root to |
()
|
Returns:
| Type | Description |
|---|---|
Decision
|
The final decision. When |
Decision
|
request; retry the same call after it is approved. |
check(principal, call, *, chain=())
¶
Dry run: decide a call without any side effect.
Nothing is written to the audit log, no budget is used and no approval is created or consumed. Use it to ask "would this be allowed?".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
principal
|
Principal
|
The agent making the call. |
required |
call
|
ToolCall
|
The tool call to check. |
required |
chain
|
Sequence[Grant]
|
Grants from the root to |
()
|
Returns:
| Type | Description |
|---|---|
Decision
|
The decision |
Decision
|
and an already-approved call still shows as |
approve(approval_id, *, approver_id, approve=True)
¶
Approve or deny a pending request on behalf of an approver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
approval_id
|
str
|
Id from the |
required |
approver_id
|
str
|
Who is answering. It must satisfy the rule's |
required |
approve
|
bool
|
True to approve, False to deny. |
True
|
Returns:
| Type | Description |
|---|---|
ApprovalStatus
|
The new status of the request. If the approver is not allowed to answer (the |
ApprovalStatus
|
requester itself, or someone the rule's |
ApprovalStatus
|
stays |
ApprovalStatus
|
approvers can be satisfied through this method; |
Raises:
| Type | Description |
|---|---|
CastellanError
|
|
Values¶
These immutable pydantic models flow in and out of the guard.
agent_castellan.ToolCall
¶
Bases: BaseModel
The thing being authorized: one tool invocation with its arguments.
Attributes:
| Name | Type | Description |
|---|---|---|
tool |
str
|
Namespaced tool name such as |
args |
dict[str, Any]
|
JSON-serializable arguments the tool will receive. |
resource |
dict[str, Any]
|
Optional extra attributes about the target; kept in the audit log. |
cost_units |
float
|
Cost of this call, counted against |
agent_castellan.Principal
¶
Bases: BaseModel
An agent identity within one run.
A principal is immutable. Create the root one with Guard.start_run and child ones
with Guard.delegate; you rarely build one by hand.
Attributes:
| Name | Type | Description |
|---|---|---|
agent_id |
str
|
Unique id of this agent instance. |
role |
str
|
Role name, as used in |
run_id |
str
|
Id shared by every agent in one delegation tree. |
parent_id |
str | None
|
|
parent_role |
str | None
|
Role of that parent, if any. |
depth |
int
|
Distance from the root agent; the root has depth 0. |
on_behalf_of |
str | None
|
Id of the end user the whole run acts for, if any. |
agent_castellan.Decision
¶
Bases: BaseModel
The outcome of authorizing a tool call.
Attributes:
| Name | Type | Description |
|---|---|---|
effect |
Effect
|
|
reason |
str
|
Human-readable explanation, taken from the rule's |
rule_id |
str | None
|
Id of the winning rule, or |
source |
str
|
Which part of the pipeline decided: |
trace |
tuple[TraceStep, ...]
|
One step per rule considered, in file order. |
approval_id |
str | None
|
Id of the pending approval request when |
agent_castellan.TraceStep
¶
Bases: BaseModel
One rule considered during a decision, and why it did or did not match.
Attributes:
| Name | Type | Description |
|---|---|---|
rule_id |
str
|
Id of the rule that was considered. |
matched |
bool
|
True if the rule's |
detail |
str
|
Short reason, such as |
agent_castellan.Effect
¶
Bases: str, Enum
What a rule or decision says should happen to a tool call.
Attributes:
| Name | Type | Description |
|---|---|---|
ALLOW |
The call may run. |
|
DENY |
The call must not run. |
|
ASK |
The call may run only after an approver says yes. |
agent_castellan.Grant
¶
Bases: BaseModel
A signed delegation from a parent agent to a child agent.
Grants form a chain from the root to the acting agent. Each grant can only narrow the one before it.
Attributes:
| Name | Type | Description |
|---|---|---|
grant_id |
str
|
Unique id of this grant. |
issuer_agent_id |
str
|
Agent that issued the grant (the parent). |
subject_agent_id |
str
|
Agent that receives the grant (the child). |
subject_role |
str
|
Role of the child. |
run_id |
str
|
Run the grant belongs to; it is useless in any other run. |
tools |
tuple[str, ...]
|
Tool globs the child may use, always a subset of the parent's. |
when |
dict[str, Any] | None
|
Extra conditions, in the same language as a rule's |
expires_at |
datetime
|
Moment after which the grant stops working. |
max_calls |
int | None
|
Maximum calls allowed under this grant, or |
signature |
str
|
Hex HMAC that chains this grant to the ones before it. |
agent_castellan.ApprovalRequest
¶
Bases: BaseModel
A pending request for a human or agent to approve one exact call.
Attributes:
| Name | Type | Description |
|---|---|---|
approval_id |
str
|
Id to pass to |
principal |
Principal
|
The agent that asked. |
call |
ToolCall
|
The call that needs approval. |
call_hash |
str
|
SHA-256 of the normalized tool name and arguments; an approval only unlocks a call with this exact hash. |
approver |
str
|
Who may approve: |
rule_id |
str
|
The |
created_at |
datetime
|
When the request was created. |
expires_at |
datetime
|
When the request stops being usable. |
agent_castellan.ApprovalStatus
¶
Bases: str, Enum
Lifecycle state of an approval request.
A request starts as PENDING, becomes APPROVED, DENIED or EXPIRED, and an
approved request becomes CONSUMED the one time it unlocks a call.
agent_castellan.AuditEntry
¶
Bases: BaseModel
One hash-chained record in the audit log.
Attributes:
| Name | Type | Description |
|---|---|---|
seq |
int
|
Position in the log, starting at 0. |
at |
datetime
|
When the decision was recorded (UTC). |
principal |
Principal
|
The agent that made the call. |
call |
ToolCall
|
The normalized call. |
decision |
Decision
|
What the guard decided. |
prev_hash |
str
|
|
hash |
str
|
SHA-256 over |
Errors¶
All Castellan errors derive from CastellanError.
agent_castellan.CastellanError
¶
Bases: Exception
Base class for every error raised by Castellan.
agent_castellan.PolicyError
¶
Bases: CastellanError
A policy file is invalid; the message names the file, line and rule.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
The problem, without the location prefix. |
|
file |
Policy file name, when known. |
|
line |
1-based line number, when known. |
|
rule_id |
Id of the offending rule, when the problem is inside a rule. |
The string form is <file>:<line> rule '<id>': <message>.
agent_castellan.GrantError
¶
Bases: CastellanError
A delegation grant is invalid, widened, expired or tampered with.
Also raised when the root key is too short or not valid hex.
agent_castellan.PermissionDenied
¶
Bases: CastellanError
A tool call was denied.
Attributes:
| Name | Type | Description |
|---|---|---|
decision |
The full decision, including |
agent_castellan.ApprovalRequired
¶
Bases: CastellanError
A tool call needs approval before it can run.
Attributes:
| Name | Type | Description |
|---|---|---|
approval_id |
Id to approve with |
|
decision |
The |
agent_castellan.BudgetExceeded
¶
Bases: CastellanError
A run, role or agent budget has been used up.
Loading and evaluating policies¶
Use these when you only need decisions, without grants, approvals, budgets or auditing.
agent_castellan.policy.loader.load_policy(path)
¶
Load and validate a policy file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path of the YAML policy. |
required |
Returns:
| Type | Description |
|---|---|
Policy
|
The validated, immutable policy. |
Raises:
| Type | Description |
|---|---|
PolicyError
|
The file cannot be read, is not valid YAML, or breaks the policy
schema. The message starts with |
agent_castellan.policy.loader.load_policy_text(text, *, source='<string>')
¶
Load and validate a policy from YAML text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The YAML document. |
required |
source
|
str
|
Name used in error messages in place of a file name. |
'<string>'
|
Returns:
| Type | Description |
|---|---|
Policy
|
The validated, immutable policy. |
Raises:
| Type | Description |
|---|---|
PolicyError
|
The text is not valid YAML or breaks the policy schema. |
agent_castellan.policy.engine.PolicyEngine
¶
Decides tool calls according to a loaded policy.
Implements the decision algorithm: deny overrides ask, ask overrides allow, and
defaults.effect applies when nothing matches. Use it directly when you only need
decisions (no grants, approvals, budgets or audit); use Guard for the full pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
Policy
|
A policy from |
required |
clock
|
Clock | None
|
Time source for |
None
|
run_tool_calls
|
Callable[[str], int] | None
|
Callback returning the number of calls made so far in a run, used
by |
None
|
Raises:
| Type | Description |
|---|---|
PolicyError
|
A rule cannot be compiled. |
Example
decide(principal, call)
¶
Return the policy decision for this call.
The call is normalized first (lower-cased tool name, resolved paths, canonical URLs).
A call that cannot be normalized is denied with reason invalid_call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
principal
|
Principal
|
The agent making the call. |
required |
call
|
ToolCall
|
The tool call to decide. |
required |
Returns:
| Type | Description |
|---|---|
Decision
|
A decision whose |
approver_for(rule_id)
¶
Return the approver string configured on a rule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule_id
|
str
|
Id of an |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Raises:
| Type | Description |
|---|---|
PolicyError
|
No rule has this id. |
can_delegate(parent_role, child_role, depth)
¶
Say whether a role at this depth may delegate to a child role.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent_role
|
str
|
Role that wants to delegate. |
required |
child_role
|
str
|
Role it wants to create. |
required |
depth
|
int
|
Depth of the parent; the child would sit at |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the parent's |
bool
|
within the parent's |
agent_castellan.policy.schema.Policy
¶
Bases: BaseModel
A loaded, validated policy: the typed form of a policy YAML document.
Attributes:
| Name | Type | Description |
|---|---|---|
version |
Literal[1]
|
Policy language version; always 1. |
defaults |
Defaults
|
What happens when no rule matches. |
agents |
dict[str, AgentConfig]
|
Role definitions, keyed by role name. |
rules |
tuple[Rule, ...]
|
Rules in file order. |
budgets |
BudgetsConfig
|
Run and per-role limits. |
approvals |
ApprovalsConfig
|
Approval settings. |
audit |
AuditConfig
|
Audit log settings. |
source |
str | None
|
File the policy was loaded from, if any. |
agent_castellan.policy.schema.Rule
¶
Bases: BaseModel
One allow, deny or ask rule.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique name, shown in decisions, traces and audit entries. |
description |
str | None
|
Free-text note for humans. |
agents |
tuple[str, ...]
|
Roles the rule applies to; |
tools |
tuple[str, ...]
|
Tool globs the rule applies to. |
when |
dict[str, Any] | None
|
Optional condition tree; see the policy language reference. |
effect |
Effect
|
|
reason |
str | None
|
Message returned in the decision. |
approver |
str
|
For |
priority |
int
|
Tie-breaker between matching rules of the same effect; higher wins. |
line |
int | None
|
Line in the source file, filled in by the loader. |
Decorator integration¶
agent_castellan.integrations.decorator.guarded(guard, *, tool)
¶
Wrap a function so every call is authorized before it runs.
The function's bound arguments become the call's args. Works for plain and async
functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guard
|
Guard
|
The guard that makes the decision. |
required |
tool
|
str
|
Tool name the policy sees, for example |
required |
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
A decorator. The wrapped function raises before running when the call is not |
Callable[[F], F]
|
allowed. |
Raises:
| Type | Description |
|---|---|
PermissionDenied
|
(from the wrapped function) the call was denied. |
ApprovalRequired
|
(from the wrapped function) the call needs approval; retry the same call once it has been approved. |
CastellanError
|
(from the wrapped function) no |
agent_castellan.integrations.decorator.guard_context(principal, chain=())
¶
Set the acting principal and grant chain for @guarded calls inside the block.
The context is stored in a contextvars.ContextVar, so it follows threads and asyncio
tasks correctly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
principal
|
Principal
|
The agent on whose behalf calls are made. |
required |
chain
|
Sequence[Grant]
|
Grants from the root to |
()
|
See integrations for the MCP proxy and the LangGraph wrapper.
Audit log¶
agent_castellan.audit.log.AuditLog
¶
Append-only, tamper-evident decision log in JSON Lines format.
Each entry stores the hash of the previous one, so editing or removing an entry in the
middle of the file is detected by verify_log. Writers take an exclusive file lock,
so several processes can append to one log.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Log file; created (with parent directories) on the first append. |
required |
clock
|
Clock
|
Time source for the |
required |
fsync
|
bool
|
Flush every entry to disk before returning. Turn off for speed in tests. |
True
|
append(principal, call, decision)
¶
Record one decision and return the stored entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
principal
|
Principal
|
The agent that made the call. |
required |
call
|
ToolCall
|
The call that was decided. |
required |
decision
|
Decision
|
The decision reached. |
required |
Returns:
| Type | Description |
|---|---|
AuditEntry
|
The entry as written, including its |
agent_castellan.audit.verify.verify_log(path)
¶
Verify the hash chain of an audit log file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path of the JSONL log. |
required |
Returns:
| Type | Description |
|---|---|
VerifyResult
|
A result with |
VerifyResult
|
|
Raises:
| Type | Description |
|---|---|
OSError
|
The file cannot be read. |
agent_castellan.audit.verify.VerifyResult
dataclass
¶
Outcome of verifying a log.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
True if every entry is intact and in order. |
entries |
int
|
Number of entries read (before the first problem when |
bad_seq |
int | None
|
Sequence number of the first bad entry; only when |
reason |
str | None
|
|
Linting¶
agent_castellan.analysis.lint.lint_policy(policy)
¶
agent_castellan.analysis.lint.Finding
dataclass
¶
One lint finding.
Attributes:
| Name | Type | Description |
|---|---|---|
check_id |
str
|
|
severity |
str
|
|
message |
str
|
What is wrong. |
rule_id |
str | None
|
The rule concerned, if any. |
line |
int | None
|
Line of that rule in the policy file, if known. |
Pitfalls¶
- Creating a
Guardper call. Build one at start-up and share it. Approvals and budgets live inside it (or in its SQLite state file). - Ignoring
ask.authorizereturns aDecisionand does not raise. If you treat anything butdenyas success you will run calls that still need approval. Checkdecision.effect is Effect.ALLOW, or use@guarded, which raises for you. - Random keys across processes. Pass the same
key=(orCASTELLAN_KEY) to every process that creates or verifies grants. - Calling
checkinstead ofauthorize.checkis a dry run and leaves no audit entry.
Where to go next¶
- Concepts: what each model means.
- Multi-agent delegation and approvals.
- CLI reference: the same engine from a terminal.