Protect your AI agents with easy peasy RBAC in minutesβno extra infrastructure.
pip install 'd2[all]'Installation options: The [all] extra includes CLI commands (d2 init, d2 diagnose, d2 publish) plus file watching for development.
Production: Use pip install d2 for runtime-only (no CLI). Or 'd2[cli]' for just CLI tools.
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.
Advanced: D2 also supports guardrails (input/output validation) and sequence tracking to prevent dangerous tool call chains. Learn more β
D2 automatically scans your code and creates a policy template with all your protected functions:
python -m d2 initCode 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' blockSecurity Note: Always ensure context is cleared to prevent leaks. You have three safe options:
with d2.set_user_context() or with d2.run_as() β Context managers@clear_context or @clear_context_async β Decoratorstry/finally with clear_user_context()See the Context Management section for detailed examples.
Your AI agents are now protected by easy peasy 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