Quick Start

Get started with D2 in 5 minutes

Protect your AI agents with enterprise-grade RBAC in minutes—no extra infrastructure.

1

Install D2

bash
pip install d2-python
2

Add decorators to your functions

Protect your AI agent functions by adding the @d2_guard decorator:

pythonyour_app.py
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.

3

Generate your policy template

D2 automatically scans your code and creates a policy template with all your protected functions:

bash
python -m d2 init
🔍

Code Analysis: D2 finds all your @d2_guard decorators and automatically generates a policy file at ~/.config/d2/policy.yaml

4

Configure D2 in your app

Initialize D2 once at startup and set user context for each request:

pythonmain.py
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.

You're all set!

Your AI agents are now protected by enterprise-grade authorization. Functions will be blocked by default until you grant permissions in your policy file.

What happens next?

  • Protected functions will raise PermissionDeniedError until authorized
  • Edit your policy file to grant permissions to specific roles
  • Use python -m d2 inspect to validate your policy