Protect your AI agents with enterprise-grade RBAC in minutes—no extra infrastructure.
pip install d2-python
Protect your AI agent functions by adding the @d2_guard
decorator:
import d2
@d2.d2_guard("weather_api")
def get_weather(location: str):
"""Get weather for a location"""
return weather_service.fetch(location)
@d2.d2_guard("send_email")
def send_notification(recipient: str, message: str):
"""Send email notification"""
return email_service.send(recipient, message)
@d2.d2_guard("database_query")
def query_user_data(user_id: str):
"""Query sensitive user data"""
return database.query(f"SELECT * FROM users WHERE id = {user_id}")
Pro tip: Add decorators to all functions that your AI agents will call. This includes API calls, database queries, file operations, and external service interactions.
D2 automatically scans your code and creates a policy template with all your protected functions:
python -m d2 init
Code Analysis: D2 finds all your @d2_guard
decorators and automatically generates a policy file at ~/.config/d2/policy.yaml
Initialize D2 once at startup and set user context for each request:
import d2
# Initialize D2 (call once at startup)
await d2.configure_rbac_async()
# For each request/interaction, set the user context
def handle_request(user_id: str, user_roles: list):
# Set user context (IMPORTANT: use context manager for safety)
with d2.set_user_context(user_id, user_roles):
# Now your protected functions will check permissions
weather = get_weather("San Francisco")
send_notification(user_id, f"Weather: {weather}")
# Context automatically cleared when exiting the 'with' block
Security Note: The easiest way to avoid context leaks is to wrap each request in with d2.set_user_context()
so cleanup is automatic. If you call d2.set_user()
directly, remember to call d2.clear_user_context()
before returning. For a deeper explanation see the Context Management section of the full docs.
Your AI agents are now protected by enterprise-grade authorization. Functions will be blocked by default until you grant permissions in your policy file.
PermissionDeniedError
until authorizedpython -m d2 inspect
to validate your policy