Skip to content

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
guard = Guard.from_file("policy.yaml", key=secrets.token_bytes(32))
me = guard.start_run("planner")
decision = guard.authorize(me, ToolCall(tool="fs.read", args={"path": "/workspace/a"}))

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 authorize decision.

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 CASTELLAN_KEY environment variable is used; if that is unset too, a random key is generated for this process and a RuntimeWarning is emitted.

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 castellan approve.

None

Returns:

Type Description
Guard

A fully wired guard. The audit log is written to the policy's audit.path.

Raises:

Type Description
PolicyError

The policy file cannot be read or is invalid.

GrantError

The key is shorter than 32 bytes or CASTELLAN_KEY is not hex.

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 planner.

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 run_id.

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 ["fs.read", "web.*"].

required
when dict[str, Any] | None

Extra conditions in the rule when language, ANDed with the parent's.

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 budgets section to cap usage today.

None

Returns:

Type Description
Principal

The child principal and its signed grant. Pass the grant (or the chain)

Grant

to authorize, or let the guard remember it for you.

Raises:

Type Description
PermissionDenied

The policy does not let parent.role delegate to child_role at this depth.

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 principal. Optional for agents created by this guard's delegate, which remembers the chain.

()

Returns:

Type Description
Decision

The final decision. When effect is ask, approval_id names the new

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 principal; see authorize.

()

Returns:

Type Description
Decision

The decision authorize would reach, except that an ask has no approval_id

Decision

and an already-approved call still shows as ask.

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 ask decision.

required
approver_id str

Who is answering. It must satisfy the rule's approver and must not be the agent that asked.

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 approver does not name), the request

ApprovalStatus

stays PENDING and no error is raised. Today only human and agent:<id>

ApprovalStatus

approvers can be satisfied through this method; role:<role> approvers cannot.

Raises:

Type Description
CastellanError

approval_id is unknown.

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 fs.write or mcp:filesystem/read_file. Names are lower-cased and checked before any rule is evaluated.

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 max_cost_units budgets.

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 agents: and in rule agents: lists.

run_id str

Id shared by every agent in one delegation tree.

parent_id str | None

agent_id of the agent that delegated to this one, if any.

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

allow, deny or ask.

reason str

Human-readable explanation, taken from the rule's reason when it has one.

rule_id str | None

Id of the winning rule, or None when a default, grant or budget decided.

source str

Which part of the pipeline decided: policy, default, grant, budget, approval or invalid.

trace tuple[TraceStep, ...]

One step per rule considered, in file order.

approval_id str | None

Id of the pending approval request when effect is ask.

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 agents, tools and when all matched.

detail str

Short reason, such as tools: no match for 'fs.write'.

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 when.

expires_at datetime

Moment after which the grant stops working.

max_calls int | None

Maximum calls allowed under this grant, or None for no limit.

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 Guard.approve.

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: human, role:<role> or agent:<id>.

rule_id str

The ask rule that created the request.

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 of the previous entry; 64 zeros for the first entry.

hash str

SHA-256 over prev_hash and this entry's canonical JSON.

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 reason, rule_id and trace.

agent_castellan.ApprovalRequired

Bases: CastellanError

A tool call needs approval before it can run.

Attributes:

Name Type Description
approval_id

Id to approve with Guard.approve or castellan approve accept.

decision

The ask decision, when available.

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 <file>:<line> and names the rule.

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 load_policy.

required
clock Clock | None

Time source for time.* conditions; defaults to the system clock in UTC.

None
run_tool_calls Callable[[str], int] | None

Callback returning the number of calls made so far in a run, used by run.tool_calls conditions. Without it that path is always 0.

None

Raises:

Type Description
PolicyError

A rule cannot be compiled.

Example
engine = PolicyEngine(load_policy("policy.yaml"))
decision = engine.decide(principal, ToolCall(tool="fs.read", args={"path": "/a"}))

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 trace has one step per rule, in file order.

approver_for(rule_id)

Return the approver string configured on a rule.

Parameters:

Name Type Description Default
rule_id str

Id of an ask rule.

required

Returns:

Type Description
str

human, role:<role> or agent:<id>.

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 depth + 1.

required

Returns:

Type Description
bool

True if the parent's can_delegate_to lists the child and the child's depth is

bool

within the parent's max_delegation_depth.

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; ("*",) means all.

tools tuple[str, ...]

Tool globs the rule applies to.

when dict[str, Any] | None

Optional condition tree; see the policy language reference.

effect Effect

allow, deny or ask.

reason str | None

Message returned in the decision.

approver str

For ask rules: human, role:<role> or agent:<id>.

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 fs.read.

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 guard_context is active.

Example
@guarded(guard, tool="fs.read")
def read_file(path: str) -> str: ...

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 principal; leave empty for a root agent or for agents created by the same guard's delegate.

()
Example
with guard_context(principal):
    read_file("/workspace/a.txt")

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 at field.

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 seq, prev_hash and hash.

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 ok=True and the entry count, or ok=False with the first bad

VerifyResult

seq and a reason: hash_mismatch, gap or reordered.

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 ok is False).

bad_seq int | None

Sequence number of the first bad entry; only when ok is False.

reason str | None

hash_mismatch, gap or reordered; only when ok is False.

Linting

agent_castellan.analysis.lint.lint_policy(policy)

Run every lint check against a policy.

Parameters:

Name Type Description Default
policy Policy

A policy from load_policy.

required

Returns:

Type Description
list[Finding]

All findings, grouped by check id. An empty list means the policy is clean.

agent_castellan.analysis.lint.Finding dataclass

One lint finding.

Attributes:

Name Type Description
check_id str

L001 to L007.

severity str

error (makes castellan lint exit 1) or warning.

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 Guard per call. Build one at start-up and share it. Approvals and budgets live inside it (or in its SQLite state file).
  • Ignoring ask. authorize returns a Decision and does not raise. If you treat anything but deny as success you will run calls that still need approval. Check decision.effect is Effect.ALLOW, or use @guarded, which raises for you.
  • Random keys across processes. Pass the same key= (or CASTELLAN_KEY) to every process that creates or verifies grants.
  • Calling check instead of authorize. check is a dry run and leaves no audit entry.

Where to go next