evaluate() call consults direct permissions, delegated permissions, role memberships, and ReBAC relationship tuples, then combines the results with a configurable combining algorithm.
Use the policy engine when you need to make authorization decisions that depend on org membership, relationship graphs, or delegation chains. theauth.authorize() is a separate code path: it shares the ABAC primitives (resource matching and constraint checks) with the policy engine, but it evaluates only the first matching permission on the agent, then falls back to permissions received through delegation. It does not call evaluate(), and it does not do role expansion or ReBAC checks. Call evaluate() directly when you want those, combine-all semantics, or richer decision metadata.
Quick start
createPolicyEngine is an internal factory, it is not part of the public API surface. Access the engine through theauth.policy on a constructed TheAuth instance instead, it is always available (zero-config uses safe defaults).The PolicyDecision shape
Everyevaluate() call returns a PolicyDecision. Never throw on a denied decision inside the engine: all failures, including validation errors, return allowed: false with a reason code.
What it combines
Direct and delegated permissions
For agent subjects, the engine fetches permissions stored directly on the agent (via thepermissions table) and permissions received through active, non-expired delegation chains. Delegated permissions reach the engine with their constraints, and the constraints are applied. delegate() stores them narrowed against the parent: requireApproval is OR-ed, maxCallsPerHour takes the lower value, and allowedArgPatterns and ipAllowlist are intersected. A permission whose constraint requires approval makes the decision escalate, not deny.
Unlike authorize(), the engine evaluates every matching permission (not just the first) and combines the results.
Role-derived permissions
For user subjects (whensubject.userId is present), the engine joins orgMembers to orgRoles and folds the resulting permissions into the effective set. Role permissions are stored as resource:action strings (split on the last colon). Supply subject.orgId to scope the lookup to a specific org; without it the engine considers all orgs the user belongs to.
ReBAC relationships
When a permission hasrelation set, the engine makes a graph query against the rebacRelationships table before counting that permission as a match.
(subject, "viewer", resource) is satisfied, including inherited relations from parent objects. The requested resource must be a concrete type:id (for example document:123); a resource containing * never matches a relation. Set only one of agentId or userId on the subject for relation checks, because a subject with both is treated as invalid and does not match. If no tuple matches, the permission is skipped. It does not contribute a PERMIT or DENY, the next permission in the effective set is checked instead.
If the graph query itself fails (database error or depth limit exceeded), the engine records POLICY_GRAPH_QUERY_FAILED and returns indeterminate rather than accidentally granting access. The engine is fail-closed on graph errors.
Risk tiers and escalation
A permitted action can still need a human. Pass typed risk attributes ascontext.risk and configure tier rules under policy.risk.tiers. After permission matching, the strongest matching tier decides what the action requires: none, approval or step_up. An allow that lands in an approval or step_up tier becomes escalate. Deny and escalate results pass through unchanged. Risk is applied after the cache, so it never changes cached decisions.
RiskContext fields are amount, currency, dataClass, irreversible and extras. A rule matches only when every field in its when holds: minAmount, currency, dataClasses and irreversible. The caller supplies the risk values; the engine does not derive them. The amount threshold is this tier rule, not a numeric constraint on a permission, and cumulative spend is not tracked.
With openApproval: true, an escalation opens a request through the approval module for the agent’s owner (or subject.userId) and returns its id on escalation.approvalRequestId. If the request cannot be stored, the decision stays escalate without an id. It never becomes an allow. The decision stays escalate after a human approves until you call evaluate again with approvalId set to that request id. evaluate then verifies the approval, spends it (single use) and returns allow, or returns deny with APPROVAL_NOT_FOUND, APPROVAL_NOT_APPROVED, APPROVAL_MISMATCH, APPROVAL_EXPIRED or APPROVAL_ALREADY_USED. See Approval flows.
Owner binding and inactive agents
Before the cache is consulted,evaluate() checks the agent row:
- A revoked, suspended or expired agent is denied with
POLICY_AGENT_INACTIVE. - If
subject.ownerIdis set and differs from the agent’sownerId, the decision isPOLICY_OWNER_MISMATCH. If the agent does not exist andownerIdis set, the same code is returned.
subject.ownerId and no owner check runs. Take the value from the authenticated request, not from agent input.
Caching
The engine keeps a process-local LRU cache. Defaults are 10,000 entries and a 60-second TTL. Configure via environment variables:
Or pass config directly through
createTheAuth():
evaluate() call with the same key is served from the cache with cacheHit: true. Validation errors, subject lookup failures, and graph query failures are not cached.
What does not get cached: Permissions with maxCallsPerHour, timeWindow, or allowedArgPatterns constraints are state or input dependent. Caching those would let a rate-limited agent exceed its limit, let a timed-out permission linger past its window, or let a safe-arguments decision serve an unsafe-arguments request (arguments are not part of the key). The engine skips the cache write for any evaluation where a matching permission carries one of these constraints.
Invalidation: TTL expiry happens lazily on read. For immediate invalidation after a write:
invalidate() does not affect other processes. Permissions granted or revoked will take up to ttlMs to propagate naturally via TTL expiry across all instances. See Limitations.
Cache statistics are available for dashboards and benchmark assertions:
Combining algorithm
The default strategy is deny-overrides. Every matching permission produces a PERMIT (constraints pass) or a DENY (a constraint fails); permissions that do not match the resource or action, or whose ReBAC relation is not satisfied, produce nothing. Any DENY wins over any number of PERMITs. This reflects the conservative principle: if any rule says no, the answer is no. A worked example:perm-1 would allow the call in isolation, the time-window constraint on perm-2 produces a DENY, and deny-overrides means the final answer is no.
If no permission matched at all, the result is indeterminate with reason POLICY_NO_MATCHING_PERMISSION, and allowed is false. Callers should treat indeterminate the same as an explicit deny.
To flip to permit-overrides (any PERMIT wins over DENYs), pass combineStrategy: "permit-overrides" in the policy config. That is less common; most deployments want the conservative default.
Audit
Everyevaluate() call with an agentId in the subject writes one audit row to audit_logs, including cache hits. The cache_hit column distinguishes hot from cold decisions in dashboards. The result column is allowed, denied or escalated. The row stores the final decision after risk tiers, so an escalation is never logged as an allow. It also carries subject_id (the accountable human), actor_id, policy_version (from policyVersion) and delegation_chain when the agent acts through a delegation. The row is written through the same writer as other audit rows, so with audit.tamperEvident on it joins the agent’s hash chain. Calls rejected by input validation, and calls where the agent has no owner, write no row.
auditSampleRate defaults to 1.0 (every evaluation). Dial it down in high-throughput environments where a hot cache path would otherwise generate millions of rows per hour.
Current limitation: Only evaluations with an agentId in the subject write audit rows. The audit_logs table has agent_id NOT NULL, so user-only subjects (where only userId is present) are silently skipped.
Audit writes are non-blocking. A write failure does not affect the returned decision, but it is counted by getAuditWriteFailures and reported to audit.onAuditError, and the next successful write is preceded by an audit.write_failed row. A write that fails is not retried. The auditId on the decision is generated before the write, so it can refer to a row that was never written if the insert failed. It is undefined when audit is disabled, the sample excluded the call, or the subject has no agentId.
Configuration
FullPolicyEngineConfig reference:
How to combine PERMIT and DENY results from multiple matching permissions.
Tier rules
{ tier, when, require }. require is none, approval or step_up. The strongest match wins.Label for the active policy set, written to the
policy_version field of each audit row. You choose the value.Migration from authorize()
authorize() still works and is the path adapters use. It does not call evaluate() internally, so the two can disagree: authorize() stops at the first permission matching resource and action, while evaluate() considers all matching permissions (deny-overrides) and also reads roles and ReBAC relations. Also, authorize() takes the request context as an optional third argument, while evaluate() takes context inside its input.
If you want the full PolicyDecision (cache hit, matched relation, duration), call evaluate() directly:
requireScopes() in mcp/require-scopes.ts still uses its own code path. It does not yet call evaluate().
Performance targets and benchmarks
Design targets (not guarantees; run the benchmark on your own hardware):
The benchmark suite lives at
packages/core/bench/policy-engine.bench.ts and uses tinybench. Run it locally:
Limitations and follow-ups
These are known gaps in v1, tracked for future work: Process-local cache only.invalidate() affects only the current process. In a multi-instance deployment, stale entries persist in other processes until TTL expiry. A KV or Redis cache layer can slot in later through the same PolicyCache interface, but it is not implemented yet.
No auto-invalidation on writes. Nothing calls invalidate() when permissions, delegation chains, org roles, org members, or ReBAC relationships change. Callers must call engine.invalidate() manually after mutations that should take effect immediately.
User-only subjects skip audit. If subject.agentId is absent, no audit row is written. This is a schema constraint (audit_logs.agent_id NOT NULL), not a policy choice.
No declarative policy DSL. Permissions are plain typed objects. Cedar, Rego, and Casbin-style rule languages are out of scope for v1. Permissions stay as structured data.
requireScopes() is not wired. MCP scope checks in mcp/require-scopes.ts still use their own path and do not call evaluate(). The combining and caching benefits of the policy engine do not apply to scope checks yet.
Related
Permissions
Direct permissions, constraints, and templates.
ReBAC
Relationship graph, hierarchy traversal, and tuple management.
Delegation
Grant permission subsets between agents.
Audit trail
How decisions are logged and surfaced in the dashboard.