### Minimal Tornado example with tornadoapi-guard Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/tornado.md Complete example showing how to set up SecurityMiddleware and SecurityDecorator, initialize the agent, and run a Tornado server. Requires GUARD_API_KEY and GUARD_PROJECT_ID environment variables; defaults to https://api.guard-core.com for the core URL. Calls initialize() to start the agent and reset() on shutdown. ```python import asyncio import os import tornado.httpserver import tornado.web from tornadoapi_guard import SecurityConfig, SecurityDecorator, SecurityMiddleware class RootHandler(tornado.web.RequestHandler): async def get(self) -> None: self.write({"message": "Hello, Guard!"}) def build_application( middleware: SecurityMiddleware, decorator: SecurityDecorator ) -> tornado.web.Application: return tornado.web.Application( [(r"/", RootHandler)], security_middleware=middleware, guard_decorator=decorator, ) async def main() -> None: api_key = os.environ.get("GUARD_API_KEY", "") project_id = os.environ.get("GUARD_PROJECT_ID", "") core_url = os.environ.get("GUARD_CORE_URL", "https://api.guard-core.com") security_config = SecurityConfig( # Security settings auto_ban_threshold=5, auto_ban_duration=300, enable_rate_limiting=True, rate_limit=100, rate_limit_window=60, # Agent telemetry enable_agent=bool(api_key), agent_api_key=api_key, agent_endpoint=core_url, agent_project_id=project_id, ) security_middleware = SecurityMiddleware(config=security_config) guard_decorator = SecurityDecorator(security_config) security_middleware.set_decorator_handler(guard_decorator) # initialize() starts the agent (and everything else) on the current event loop. await security_middleware.initialize() app = build_application(security_middleware, guard_decorator) server = tornado.httpserver.HTTPServer(app) server.listen(8000, address="127.0.0.1") try: await asyncio.Event().wait() # Run forever finally: await security_middleware.reset() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Install pre-commit hooks for code quality after development setup. ```bash pre-commit install ``` -------------------------------- ### Install tornadoapi-guard and guard-agent from source (poetry) Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/tornado.md Alternative installation using Poetry for the pre-release adapter and guard-agent. ```bash poetry add "git+https://github.com/Guard-Core/tornadoapi-guard.git" poetry add guard-agent ``` -------------------------------- ### Install guard-agent with uv Source: https://github.com/guard-core/guard-agent/blob/master/README.md Install guard-agent using uv. This is the recommended installation method for new projects; the legacy name fastapi-guard-agent is still published as a meta-package that installs guard-agent transitively. ```bash uv add guard-agent ``` -------------------------------- ### Install flaskapi-guard and guard-agent with Poetry Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/flask.md Alternative installation command using Poetry. ```bash poetry add flaskapi-guard guard-agent ``` -------------------------------- ### Install tornadoapi-guard and guard-agent from source (pip) Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/tornado.md Alternative installation using pip for the pre-release adapter and guard-agent. ```bash pip install "git+https://github.com/Guard-Core/tornadoapi-guard.git" pip install guard-agent ``` -------------------------------- ### Install guard-agent with Poetry Source: https://github.com/guard-core/guard-agent/blob/master/README.md Alternative installation method using Poetry. Use this if your project is managed with Poetry. ```bash poetry add guard-agent ``` -------------------------------- ### Install flaskapi-guard and guard-agent with pip Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/flask.md Alternative installation command using pip. ```bash pip install flaskapi-guard guard-agent ``` -------------------------------- ### Install tornadoapi-guard and guard-agent from source (uv) Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/tornado.md Installs the pre-release tornadoapi-guard adapter from GitHub and guard-agent using uv. Use this during the pre-release window since the adapter is not yet on PyPI. ```bash uv pip install "git+https://github.com/Guard-Core/tornadoapi-guard.git" uv add guard-agent ``` -------------------------------- ### Install djapi-guard and guard-agent with Poetry Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/django.md Alternative installation command using Poetry. Use this instead of uv when your project is managed with Poetry. ```bash poetry add djapi-guard guard-agent ``` -------------------------------- ### Development installation from source Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Clone the repository and sync development dependencies for contributors and advanced users requiring source access. ```bash git clone https://github.com/Guard-Core/guard-agent.git cd guard-agent uv sync --extra dev ``` -------------------------------- ### Install tornadoapi-guard and guard-agent from PyPI (uv) Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/tornado.md Once the adapter is published, use this plain form with uv. ```bash uv add tornadoapi-guard guard-agent ``` -------------------------------- ### Install guard-agent with pip Source: https://github.com/guard-core/guard-agent/blob/master/README.md Alternative installation method using pip. Use this if your project uses pip directly. ```bash pip install guard-agent ``` -------------------------------- ### Start FastAPI application with uvicorn Source: https://github.com/guard-core/guard-agent/blob/master/docs/tutorial/getting-started.md Starts the FastAPI application with auto-reload and info-level logging for deployment validation. ```bash uvicorn main:app --reload --log-level info ``` -------------------------------- ### Install Guard Agent with framework adapter using uv Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Install Guard Agent with the adapter for your framework using uv. Choose the appropriate command for FastAPI, Flask, Django, or Tornado. ```bash # FastAPI uv add fastapi-guard guard-agent # Flask uv add flaskapi-guard guard-agent # Django uv add djapi-guard guard-agent # Tornado uv add tornadoapi-guard guard-agent ``` -------------------------------- ### Install and register guard-core-mcp MCP server Source: https://github.com/guard-core/guard-agent/blob/master/README.md Install the guard-core-mcp MCP server as a dev dependency and register it with Claude. The server introspects the installed Guard Agent environment, so it must be installed in the same environment as Guard Agent; an isolated run (uvx) has nothing to read. ```bash uv add --dev guard-core-mcp claude mcp add guard-core -- uv run guard-core-mcp ``` -------------------------------- ### Install flaskapi-guard and guard-agent with uv Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/flask.md Installs the flaskapi-guard extension and guard-agent package using the uv package manager. ```bash uv add flaskapi-guard guard-agent ``` -------------------------------- ### Install djapi-guard and guard-agent with pip Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/django.md Alternative installation command using pip. Use this when you manage dependencies with pip. ```bash pip install djapi-guard guard-agent ``` -------------------------------- ### Switch install command from fastapi-guard-agent to guard-agent with uv Source: https://github.com/guard-core/guard-agent/blob/master/README.md Commands to switch the install command from the legacy fastapi-guard-agent package to the preferred guard-agent package using uv. The old command still works via a shim. ```bash # Old (still works via shim) uv add fastapi-guard-agent # New (preferred) uv add guard-agent ``` -------------------------------- ### Install fastapi-guard and guard-agent with uv, poetry, or pip Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/fastapi.md Add fastapi-guard and guard-agent with your preferred package manager. The uv and poetry commands add them as project dependencies, while pip installs them into the current environment. ```bash uv add fastapi-guard guard-agent ``` ```bash poetry add fastapi-guard guard-agent ``` ```bash pip install fastapi-guard guard-agent ``` -------------------------------- ### Enable Guard Agent in FastAPI with SecurityConfig Source: https://github.com/guard-core/guard-agent/blob/master/docs/tutorial/getting-started.md Standard integration pattern for enabling Guard Agent telemetry in a FastAPI application. Requires Python 3.10+, a valid API key and project ID from the FastAPI Guard management platform, and the guard package installed. The agent starts automatically when the SecurityMiddleware is added, and the /health endpoint reports whether the agent is enabled. ```python # main.py from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware app = FastAPI(title="My Secure API") # Configure FastAPI Guard with agent enabled config = SecurityConfig( # Basic security settings auto_ban_threshold=5, auto_ban_duration=300, enable_rate_limiting=True, rate_limit=100, rate_limit_window=60, # Enable agent for telemetry enable_agent=True, agent_api_key="your-api-key-here", # Replace with your actual API key agent_project_id="your-project-id", # Replace with your project ID agent_endpoint="https://api.guard-core.com", # Default SaaS endpoint # Agent configuration agent_buffer_size=100, # Buffer up to 100 events agent_flush_interval=30, # Send data every 30 seconds agent_enable_events=True, # Enable security event collection agent_enable_metrics=True, # Enable performance metrics # Enable dynamic rules from SaaS enable_dynamic_rules=True, dynamic_rule_interval=300, # Check for rule updates every 5 minutes ) # Add security middleware - agent starts automatically app.add_middleware(SecurityMiddleware, config=config) @app.get("/") async def root(): return {"message": "Hello, World!"} @app.get("/health") async def health(): return {"status": "healthy", "agent_enabled": config.enable_agent} ``` -------------------------------- ### Install guard-agent with Redis extra Source: https://github.com/guard-core/guard-agent/blob/master/README.md Install guard-agent with the Redis extra to enable the Redis-backed event buffer. This is an optional extra for multi-tier buffering with Redis persistence. ```bash uv add "guard-agent[redis]" # Enable Redis-backed event buffer ``` -------------------------------- ### Install specific Guard Agent version with uv Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Pin Guard Agent to version 2.8.0 for reproducible deployments. ```bash uv add "guard-agent==2.8.0" ``` -------------------------------- ### FastAPI example with SecurityMiddleware Source: https://github.com/guard-core/guard-agent/blob/master/README.md Use this FastAPI example to enable the guard agent via SecurityMiddleware. The middleware owns the agent lifecycle; do not construct an AgentConfig, call guard_agent(), or wire a lifespan hook here, as that creates a second agent that never receives traffic. With enable_agent=True, the agent captures violations, collects telemetry, synchronizes policies, buffers intelligently, and recovers from transient network failures. ```python import os from fastapi import FastAPI from guard import SecurityConfig, SecurityDecorator, SecurityMiddleware api_key = os.environ.get("GUARD_API_KEY", "") project_id = os.environ.get("GUARD_PROJECT_ID", "") core_url = os.environ.get("GUARD_CORE_URL", "https://api.guard-core.com") security_config = SecurityConfig( auto_ban_threshold=5, auto_ban_duration=300, enable_agent=bool(api_key), agent_api_key=api_key, agent_endpoint=core_url, agent_project_id=project_id, agent_buffer_size=100, agent_flush_interval=2, enable_dynamic_rules=bool(api_key), dynamic_rule_interval=60, ) guard = SecurityDecorator(security_config) app = FastAPI() app.add_middleware(SecurityMiddleware, config=security_config) SecurityMiddleware.configure_cors(app, security_config) app.state.guard_decorator = guard @app.get("/") async def root() -> dict[str, str]: return {"message": "Hello World"} ``` -------------------------------- ### Install djapi-guard and guard-agent with uv Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/django.md Adds the djapi-guard middleware and guard-agent packages using the uv package manager. Run this in your project root before configuring Django settings. ```bash uv add djapi-guard guard-agent ``` -------------------------------- ### Check Python version Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Verifies that Python 3.10 or higher is installed. Python 3.11+ is recommended for optimal performance and feature compatibility. ```bash python --version ``` -------------------------------- ### Install Guard Agent with pip-tools workflow Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Define the pinned version in requirements.in, then generate and sync locked requirements with pip-tools. ```text guard-agent==2.8.0 ``` ```bash pip-compile requirements.in pip-sync requirements.txt ``` -------------------------------- ### Minimal FastAPI app with Guard Agent middleware (minimal_test.py) Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Creates a FastAPI application that configures Guard Agent through SecurityConfig and attaches SecurityMiddleware. The agent starts automatically when the middleware is added. Run with: uvicorn minimal_test:app --reload ```python # minimal_test.py from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware app = FastAPI() # Configure FastAPI Guard with agent config = SecurityConfig( # Basic security enable_rate_limiting=True, rate_limit=100, # Enable agent enable_agent=True, agent_api_key="your-test-api-key", agent_project_id="your-test-project", agent_endpoint="https://api.guard-core.com" ) # Add middleware - agent starts automatically app.add_middleware(SecurityMiddleware, config=config) @app.get("/") async def root(): return {"message": "Guard Agent is running!"} @app.get("/test") async def test(): return {"agent_enabled": config.enable_agent} # Run with: uvicorn minimal_test:app --reload ``` ```bash which python pip list | grep guard-agent ``` ```bash source venv/bin/activate # Linux/Mac # or venv\Scripts\activate # Windows ``` ```bash uvicorn minimal_test:app --reload ``` -------------------------------- ### Enable Guard Agent with FastAPI adapter Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Configure and enable Guard Agent in a FastAPI application using SecurityConfig, SecurityDecorator, and SecurityMiddleware. Set auto_ban_threshold and auto_ban_duration for basic security, enable the agent with your API key and project ID, and configure agent buffering and dynamic rules. The example creates a FastAPI app, adds the middleware, and defines a root endpoint. ```python from fastapi import FastAPI from guard import SecurityConfig, SecurityDecorator, SecurityMiddleware config = SecurityConfig( # Basic security settings auto_ban_threshold=5, auto_ban_duration=300, # Enable agent for telemetry enable_agent=True, agent_api_key="YOUR_API_KEY", agent_project_id="YOUR_PROJECT_ID", agent_endpoint="https://api.guard-core.com", # Agent configuration agent_buffer_size=100, agent_flush_interval=30, agent_enable_events=True, agent_enable_metrics=True, # Enable dynamic rules from SaaS enable_dynamic_rules=True, dynamic_rule_interval=300, ) guard = SecurityDecorator(config) app = FastAPI() app.add_middleware(SecurityMiddleware, config=config) app.state.guard_decorator = guard @app.get("/") async def root(): return {"message": "Hello World"} ``` -------------------------------- ### Standard Deployment with SecurityConfig and SecurityMiddleware Source: https://github.com/guard-core/guard-agent/blob/master/docs/api/overview.md Standard deployment pattern for FastAPI Guard. Configures SecurityConfig with agent enabled and security features, then adds SecurityMiddleware to the FastAPI app. The agent starts automatically when the middleware is added. ```python from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware app = FastAPI() # Configure FastAPI Guard with agent config = SecurityConfig( # Enable agent enable_agent=True, agent_api_key="your-api-key", agent_project_id="your-project-id", # Security settings enable_rate_limiting=True, enable_ip_banning=True, enable_penetration_detection=True, ) # Add middleware - agent starts automatically app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### Package Import Validation Test (test_installation.py) Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Verifies that the Guard Agent package and its modules are importable. Prints a success message with the installed version or a failure message on ImportError. Run with: python test_installation.py ```python # test_installation.py try: # Validate Guard Agent module availability from guard_agent import __version__ from guard_agent.client import guard_agent from guard_agent.models import AgentConfig print(f"Guard Agent {__version__} successfully installed") # Validate your framework's adapter (example: FastAPI) from guard import SecurityConfig, SecurityMiddleware print("FastAPI adapter (fastapi-guard) verified") except ImportError as e: print(f"Installation validation failed: {e}") ``` ```bash python test_installation.py ``` -------------------------------- ### Standalone agent instantiation with guard_agent() Source: https://github.com/guard-core/guard-agent/blob/master/README.md Use this standalone example for custom event handling without adapter middleware in the same process. Do not use it in a process that also runs an adapter with enable_agent=True, because guard_agent() dispatches to SyncGuardAgentHandler from sync context but to GuardAgentHandler from the middleware's async init, creating separate singletons where only the middleware's instance receives traffic. Configure agent_* fields on SecurityConfig instead. ```python from guard_agent.client import guard_agent from guard_agent.models import AgentConfig config = AgentConfig( api_key="YOUR_API_KEY", project_id="YOUR_PROJECT_ID", ) agent = guard_agent(config) ``` -------------------------------- ### Production Dockerfile for Guard Agent Source: https://github.com/guard-core/guard-agent/blob/master/docs/installation.md Production Dockerfile using a multi-stage build for minimal image size. It installs uv, syncs dependencies, copies packages, and runs as a non-root user for security. ```dockerfile FROM python:3.11-slim as builder # Install uv RUN pip install --user uv ENV PATH=/root/.local/bin:$PATH # Sync project dependencies WORKDIR /build COPY pyproject.toml uv.lock* ./ RUN uv sync --frozen --no-dev FROM python:3.11-slim # Copy installed packages COPY --from=builder /root/.local /root/.local ENV PATH=/root/.local/bin:$PATH # Application setup WORKDIR /app COPY . . # Security: Run as non-root user RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app USER appuser CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] ``` -------------------------------- ### Basic Usage: Auto-integrated with FastAPI Guard Source: https://github.com/guard-core/guard-agent/blob/master/docs/api/overview.md Configure the agent via SecurityConfig and add the middleware to a FastAPI app. The agent starts automatically with the middleware. ```python from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware # Configure with agent enabled config = SecurityConfig( enable_agent=True, agent_api_key="your-api-key", agent_project_id="your-project-id", agent_endpoint="https://api.guard-core.com", ) app = FastAPI() app.add_middleware(SecurityMiddleware, config=config) # Agent starts automatically with middleware ``` -------------------------------- ### Get agent statistics with get_stats() Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Use to retrieve detailed agent statistics, including running state, events sent, transport stats, and buffer stats. ```python stats = agent.get_stats() print(f"Running: {stats['running']}") print(f"Events sent: {stats['events_sent']}") print(f"Transport stats: {stats['transport_stats']}") print(f"Buffer stats: {stats['buffer_stats']}") ``` -------------------------------- ### Use guard_agent() directly for custom event reporting Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Advanced usage pattern for specialized cases that don't go through a framework adapter. Use guard_agent() directly with AgentConfig, then manually start, send events, and stop. Warning: do not use this pattern with fastapi-guard; the factory dispatches to separate singletons for sync and async contexts, and only the middleware's instance receives the telemetry stream. ```python from guard_agent import guard_agent, AgentConfig, SecurityEvent from guard_agent.utils import get_current_timestamp # Configure agent directly config = AgentConfig( api_key="your-api-key", project_id="your-project-id", buffer_size=100, flush_interval=30, ) agent = guard_agent(config) await agent.start() # Manually send an event event = SecurityEvent( timestamp=get_current_timestamp(), event_type="custom_rule_triggered", ip_address="192.168.1.100", action_taken="logged", reason="Manual event", ) await agent.send_event(event) # At shutdown await agent.stop() ``` -------------------------------- ### Expected initialization log output Source: https://github.com/guard-core/guard-agent/blob/master/docs/tutorial/getting-started.md Expected log output confirming successful initialization of the security middleware, agent telemetry pipeline, and dynamic rule synchronization. ```text INFO: FastAPI Guard security middleware initialized INFO: Agent telemetry pipeline established INFO: Dynamic rule synchronization active ``` -------------------------------- ### Get agent status with get_status() Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Use to check agent health and performance. The status type allows healthy/degraded/failed, but get_status() currently emits only healthy or degraded. ```python status = await agent.get_status() print(f"Status: {status.status}") # type allows healthy/degraded/failed; get_status() emits only healthy or degraded today print(f"Uptime: {status.uptime}s") print(f"Events sent: {status.events_sent}") print(f"Buffer size: {status.buffer_size}") print(f"Errors: {status.errors}") ``` -------------------------------- ### Direct Usage: Advanced Source: https://github.com/guard-core/guard-agent/blob/master/docs/api/overview.md Initialize the agent directly with AgentConfig and manage its lifecycle manually. Use only when no framework adapter is present; using it alongside an adapter with enable_agent=True creates a second singleton that never receives traffic. ```python from guard_agent import guard_agent, AgentConfig # Initialize directly config = AgentConfig( api_key="your-api-key", project_id="your-project-id", ) agent = guard_agent(config) # Lifecycle await agent.start() await agent.stop() # Send data manually await agent.send_event(security_event) await agent.send_metric(performance_metric) ``` -------------------------------- ### Development Environment Configuration (config_dev.py) Source: https://github.com/guard-core/guard-agent/blob/master/docs/tutorial/getting-started.md Use this configuration for development environments. It enables the agent with a small buffer and frequent flushes for immediate feedback, and disables IP banning. Rate limiting is enabled with a higher limit for testing. ```python # config_dev.py from guard import SecurityConfig dev_config = SecurityConfig( # Development agent settings enable_agent=True, agent_api_key="dev-api-key", agent_project_id="my-app-dev", agent_buffer_size=10, # Small buffer for immediate feedback agent_flush_interval=5, # Frequent flushes for testing # Security settings for dev enable_rate_limiting=True, rate_limit=1000, # Higher limits for testing enable_ip_banning=False, # Disable banning in dev ) ``` -------------------------------- ### Configure Guard Agent settings in SecurityConfig Source: https://github.com/guard-core/guard-agent/blob/master/docs/tutorial/getting-started.md Configuration architecture showing all agent-specific settings (prefixed with agent_) and dynamic rules settings within SecurityConfig. Includes retry attempts and timeout for HTTP requests, and demonstrates how agent settings coexist with standard FastAPI Guard settings like rate limiting and IP banning. ```python from guard import SecurityConfig config = SecurityConfig( # Agent-specific settings (prefix: agent_) enable_agent=True, # Enable/disable agent agent_api_key="your-api-key", # Your SaaS platform API key agent_project_id="your-project-id", # Your project identifier agent_endpoint="https://api.guard-core.com", # SaaS platform endpoint agent_buffer_size=100, # Max events in memory buffer agent_flush_interval=30, # Seconds between data transmissions agent_enable_events=True, # Collect security events agent_enable_metrics=True, # Collect performance metrics agent_retry_attempts=3, # HTTP retry attempts agent_timeout=30, # HTTP request timeout # Dynamic rules settings enable_dynamic_rules=True, # Enable dynamic rule fetching dynamic_rule_interval=300, # Seconds between rule updates # Standard FastAPI Guard settings enable_rate_limiting=True, enable_ip_banning=True, enable_penetration_detection=True, # ... other security settings ) ``` -------------------------------- ### Configure Agent Compression with AgentConfig Source: https://github.com/guard-core/guard-agent/blob/master/docs/tutorial/getting-started.md Configures a standalone agent with gzip compression enabled by default and a threshold of 1024 bytes. Only applies when the agent is not enabled via SecurityConfig. ```python from guard_agent import guard_agent, AgentConfig config = AgentConfig( api_key="your-api-key", project_id="your-project-id", compression_enabled=True, # Default; gzip large batches compression_threshold=1024, # Skip gzip for bodies smaller than 1 KiB ) agent = guard_agent(config) ``` -------------------------------- ### Initialize agent with Redis via initialize_redis Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Enables persistent buffering for production deployments by initializing the agent with a Redis handler that implements RedisHandlerProtocol. The fastapi-guard Redis handler satisfies this protocol. Use only in a process with no adapter middleware enabling the agent through SecurityConfig. ```python from guard_agent.protocols import RedisHandlerProtocol # Supply any object implementing RedisHandlerProtocol # (the fastapi-guard Redis handler satisfies this protocol) redis_handler: RedisHandlerProtocol = your_redis_handler # Initialize agent with Redis agent = guard_agent(config) await agent.initialize_redis(redis_handler) ``` -------------------------------- ### Configure FastAPI Guard with agent and security decorators Source: https://github.com/guard-core/guard-agent/blob/master/docs/tutorial/getting-started.md Configures the FastAPI Guard decorator with agent integration, adds the security middleware, and defines endpoints with rate limiting, IP whitelisting, and country blocking. Requires a valid agent API key and project ID. Security events are automatically sent to the agent. ```python from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware, SecurityDecorator app = FastAPI(title="My Secure API with Enhanced Security") # Configure with agent config = SecurityConfig( enable_agent=True, agent_api_key="your-api-key", agent_project_id="your-project-id", # ... other settings ) guard = SecurityDecorator(config) app.add_middleware(SecurityMiddleware, config=config) app.state.guard_decorator = guard @app.get("/") async def root(): return {"message": "Hello, World!"} @app.get("/public") @guard.rate_limit(requests=5, window=60) async def public_endpoint(): """Rate limited endpoint - events sent automatically to agent.""" return {"message": "This endpoint has rate limiting"} @app.get("/admin") @guard.require_ip(whitelist=["127.0.0.1", "10.0.0.0/8"]) @guard.rate_limit(requests=2, window=300) async def admin_endpoint(): """Admin endpoint with IP restrictions - all violations logged to agent.""" return {"message": "Admin access granted"} @app.get("/api/sensitive") @guard.rate_limit(requests=3, window=600) @guard.block_countries(["CN", "RU"]) async def sensitive_api(): """Sensitive API with multiple security layers.""" return {"message": "Sensitive data accessed"} ``` -------------------------------- ### Integrate guard-agent with FastAPI Guard's SecurityMiddleware Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Primary integration pattern using FastAPI Guard's built-in agent support. Configure SecurityConfig with agent_* fields and add SecurityMiddleware to automatically initialize the agent with comprehensive event collection. ```python from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware config = SecurityConfig( # Enable agent enable_agent=True, agent_api_key="your-api-key", agent_project_id="your-project-id", # Other security settings enable_rate_limiting=True, rate_limit=100, rate_limit_window=60, ) app = FastAPI() app.add_middleware(SecurityMiddleware, config=config) # Agent automatically initialized with comprehensive event collection ``` -------------------------------- ### Create and send a SecurityEvent Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Create a SecurityEvent with fields like event_type, ip_address, and metadata, then send it via agent.send_event(). Use for security-related events such as IP bans or rate limit triggers. ```python from guard_agent.models import SecurityEvent from guard_agent.utils import get_current_timestamp event = SecurityEvent( timestamp=get_current_timestamp(), event_type="ip_banned", ip_address="192.168.1.100", country="US", user_agent="Mozilla/5.0...", action_taken="block", reason="Rate limit exceeded", endpoint="/api/v1/login", method="POST", status_code=429, response_time=0.125, metadata={"attempts": 5, "window": 60} ) await agent.send_event(event) ``` -------------------------------- ### Fetch and apply dynamic security rules Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Fetch dynamic rules with agent.get_dynamic_rules() and apply IP blacklist, endpoint rate limits, and emergency mode. Use when rules are fetched from a SaaS backend. ```python # Fetch current rules rules = await agent.get_dynamic_rules() if rules: # Apply IP blacklist if client_ip in rules.ip_blacklist: # Block request pass # Apply rate limits endpoint_limit = rules.endpoint_rate_limits.get("/api/sensitive") if endpoint_limit: requests, window = endpoint_limit # Apply endpoint-specific rate limit pass # Check emergency mode if rules.emergency_mode: # Apply stricter security measures pass ``` -------------------------------- ### Minimal Flask integration with flaskapi-guard Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/flask.md Configures the FlaskAPIGuard extension with security and agent telemetry settings. Reads GUARD_API_KEY, GUARD_PROJECT_ID, and GUARD_CORE_URL from the environment, defaulting to an empty key and project ID and the default core URL. Creates a Flask app and attaches the security decorator; no manual lifecycle management is needed because Flask is synchronous. ```python import os from flask import Flask from flaskapi_guard import FlaskAPIGuard, SecurityConfig, SecurityDecorator api_key = os.environ.get("GUARD_API_KEY", "") project_id = os.environ.get("GUARD_PROJECT_ID", "") core_url = os.environ.get("GUARD_CORE_URL", "https://api.guard-core.com") security_config = SecurityConfig( # Security settings auto_ban_threshold=5, auto_ban_duration=300, enable_rate_limiting=True, rate_limit=100, rate_limit_window=60, # Agent telemetry enable_agent=bool(api_key), agent_api_key=api_key, agent_endpoint=core_url, agent_project_id=project_id, ) app = Flask(__name__) guard_decorator = SecurityDecorator(security_config) ``` -------------------------------- ### Create and send a SecurityMetric Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Create a SecurityMetric with metric_type, value, endpoint, and tags, then send it via agent.send_metric(). Use for performance and usage metrics like request counts. ```python from guard_agent.models import SecurityMetric metric = SecurityMetric( timestamp=get_current_timestamp(), metric_type="request_count", value=100.0, endpoint="/api/v1/users", tags={"method": "GET", "status": "200"} ) await agent.send_metric(metric) ``` -------------------------------- ### Minimal FastAPI integration with SecurityConfig and SecurityMiddleware Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/fastapi.md Sets up complete FastAPI integration via SecurityConfig and SecurityMiddleware—no AgentConfig, lifespan hook, or guard_agent() call needed. The middleware automatically creates the GuardAgentHandler singleton and drives its lifecycle on app startup and shutdown. Requires GUARD_API_KEY and GUARD_PROJECT_ID environment variables. ```python import os from fastapi import FastAPI from guard import SecurityConfig, SecurityMiddleware try: from guard import __version__ as _GUARD_VERSION except ImportError: _GUARD_VERSION = None config = SecurityConfig( # Local protection (independent of the agent) enable_redis=True, redis_url="redis://localhost:6379", rate_limit=100, rate_limit_window=60, auto_ban_threshold=5, auto_ban_duration=300, enable_penetration_detection=True, # Agent telemetry enable_agent=True, agent_api_key=os.environ["GUARD_API_KEY"], agent_project_id=os.environ["GUARD_PROJECT_ID"], agent_endpoint="https://api.guard-core.com", agent_buffer_size=100, agent_flush_interval=2, agent_enable_events=True, agent_enable_metrics=True, agent_guard_version=_GUARD_VERSION, # Optional — pull dynamic rule updates from the dashboard enable_dynamic_rules=True, dynamic_rule_interval=60, ) app = FastAPI() app.add_middleware(SecurityMiddleware, config=config) ``` -------------------------------- ### EventBuffer Usage Source: https://github.com/guard-core/guard-agent/blob/master/docs/api/overview.md Create an EventBuffer with AgentConfig, optionally enable Redis durability, add events and metrics, and manually flush them. ```python from guard_agent.buffer import EventBuffer from guard_agent.models import AgentConfig, SecurityEvent # Create buffer (sizing comes from AgentConfig.buffer_size / flush_interval) config = AgentConfig(api_key="your-api-key") buffer = EventBuffer(config, flush_callback=None) # Optional Redis durability await buffer.initialize_redis(redis_client) # Add events await buffer.add_event(security_event) await buffer.add_metric(performance_metric) # Manual flush events = await buffer.flush_events() metrics = await buffer.flush_metrics() ``` -------------------------------- ### Deployment Profiles for AgentConfig Source: https://github.com/guard-core/guard-agent/blob/master/docs/api/overview.md Three deployment profiles for AgentConfig: microservice (low memory, high frequency), standard API service (balanced), and high-throughput gateway (optimized for volume). Each sets buffer_size to 100 and adjusts flush_interval accordingly. ```python # Microservice deployment (low memory, high frequency) config = AgentConfig(api_key="your-api-key", buffer_size=100, flush_interval=10) # Standard API service (balanced profile) config = AgentConfig(api_key="your-api-key", buffer_size=100, flush_interval=30) # High-throughput gateway (optimized for volume) config = AgentConfig(api_key="your-api-key", buffer_size=100, flush_interval=5) ``` -------------------------------- ### Replace fastapi-guard-agent with guard-agent using Poetry Source: https://github.com/guard-core/guard-agent/blob/master/README.md Commands to replace the legacy fastapi-guard-agent package with guard-agent using Poetry. The legacy package is maintained as a meta-package pointing to guard-agent>=2.0.0,<3.0.0. ```bash # Poetry poetry remove fastapi-guard-agent && poetry add guard-agent ``` -------------------------------- ### Retry Configuration with backoff_factor and max_delay Source: https://github.com/guard-core/guard-agent/blob/master/docs/api/overview.md Configuration for retry behavior. The delay grows as backoff_factor * 2**attempt, capped at max_delay. retry_attempts is the number of retries after the first try, so total attempts are retry_attempts + 1. ```python # Retry configuration (delay = backoff_factor * 2**attempt, capped at max_delay): retry_attempts: 3 # Retries after the first try (~retry_attempts + 1 total attempts) backoff_factor: 1.0 # Multiplier on the hardcoded 2**attempt growth max_delay: 60 # Caps maximum retry delay (no jitter) ``` -------------------------------- ### Verify agent operation with curl commands Source: https://github.com/guard-core/guard-agent/blob/master/docs/tutorial/getting-started.md Runs curl commands to verify baseline connectivity, generate security events, generate performance metrics, and check agent health. ```bash # Baseline connectivity test curl http://localhost:8000/ # Security event generation curl -X POST http://localhost:8000/api/sensitive -d "test_injection" # Performance metric generation curl http://localhost:8000/api/heavy-operation # Agent health verification curl http://localhost:8000/health ``` -------------------------------- ### Django settings.py with DjangoAPIGuard middleware and SecurityConfig Source: https://github.com/guard-core/guard-agent/blob/master/docs/adapters/django.md Configures the DjangoAPIGuard middleware and shared SecurityConfig in Django settings. Reads GUARD_API_KEY, GUARD_PROJECT_ID, and GUARD_CORE_URL from the environment, with a default core URL of https://api.guard-core.com. No custom AppConfig.ready() hook is required because the middleware handles agent wiring internally. ```python # settings.py import os from guard_core.models import SecurityConfig MIDDLEWARE = [ "djangoapi_guard.middleware.DjangoAPIGuard", "django.middleware.common.CommonMiddleware", # ... your existing middleware ... ] api_key = os.environ.get("GUARD_API_KEY", "") project_id = os.environ.get("GUARD_PROJECT_ID", "") core_url = os.environ.get("GUARD_CORE_URL", ``` -------------------------------- ### Graceful Degradation with try/except Source: https://github.com/guard-core/guard-agent/blob/master/docs/api/overview.md Wrap agent calls in a try/except to isolate failures. Logs the error and lets the application continue without interruption. ```python try: await agent.send_event(event) except Exception as e: # Agent failure doesn't break your app logger.warning(f"Agent error: {e}") # Application continues normally ``` -------------------------------- ### Performance Monitoring with SecurityMetric Source: https://github.com/guard-core/guard-agent/blob/master/docs/api/overview.md Performance monitoring pattern. Uses the singleton agent to send SecurityMetric objects for response time on success and error rate on exception. The error metric uses the exception type name as a tag. ```python from guard_agent import guard_agent, SecurityMetric from guard_agent.utils import get_current_timestamp import time # Get agent instance (singleton) agent = guard_agent(AgentConfig( api_key="your-api-key", project_id="your-project-id", )) async def monitor_endpoint_performance(): """Monitor endpoint performance and send metrics.""" start_time = time.time() try: # Your endpoint logic result = await process_request() # Success metric await agent.send_metric(SecurityMetric( timestamp=get_current_timestamp(), metric_type="response_time", value=time.time() - start_time, endpoint="/api/process", tags={"status": "success"} )) return result except Exception as e: # Error metric await agent.send_metric(SecurityMetric( timestamp=get_current_timestamp(), metric_type="error_rate", value=1.0, endpoint="/api/process", tags={"error": str(type(e).__name__)} )) raise ``` -------------------------------- ### get_dynamic_rules Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Fetches and applies dynamic security rules from your SaaS backend. Returns a rules object containing IP blacklist, endpoint rate limits, and emergency mode flag. ```APIDOC ## get_dynamic_rules ### Description Fetch and apply dynamic security rules from your SaaS backend. ### Method Async function call on the agent instance. ### Usage ```python rules = await agent.get_dynamic_rules() ``` ### Returns - **rules** (object) - Contains the following fields: - **ip_blacklist** (list) - List of IP addresses to block. - **endpoint_rate_limits** (dict) - Mapping of endpoint to a tuple of (requests, window). - **emergency_mode** (boolean) - Indicates if emergency mode is active. ### Example ```python # Fetch current rules rules = await agent.get_dynamic_rules() if rules: # Apply IP blacklist if client_ip in rules.ip_blacklist: # Block request pass # Apply rate limits endpoint_limit = rules.endpoint_rate_limits.get("/api/sensitive") if endpoint_limit: requests, window = endpoint_limit # Apply endpoint-specific rate limit pass # Check emergency mode if rules.emergency_mode: # Apply stricter security measures pass ``` ``` -------------------------------- ### Implement custom transport via TransportProtocol Source: https://github.com/guard-core/guard-agent/blob/master/docs/index.md Implements a custom transport for specialized backends by subclassing TransportProtocol and overriding its four async methods. After defining the class, assign an instance to agent.transport. Use only in a process with no adapter middleware enabling the agent through SecurityConfig. ```python from guard_agent.protocols import TransportProtocol from guard_agent.models import SecurityEvent, SecurityMetric, AgentStatus, DynamicRules class CustomTransport(TransportProtocol): async def send_events(self, events: list[SecurityEvent]) -> bool: # Your custom implementation return True async def send_metrics(self, metrics: list[SecurityMetric]) -> bool: # Your custom implementation return True async def fetch_dynamic_rules(self) -> DynamicRules | None: # Your custom implementation return None async def send_status(self, status: AgentStatus) -> bool: # Your custom implementation return True # Use custom transport agent = guard_agent(config) agent.transport = CustomTransport() ``` -------------------------------- ### Import GuardAgentHandler and AgentConfig from guard_agent Source: https://github.com/guard-core/guard-agent/blob/master/README.md Import statement for the GuardAgentHandler and AgentConfig classes from the guard_agent package. No code changes are required when migrating from fastapi-guard-agent because the import path was always guard_agent. ```python # This worked before and still works: from guard_agent import GuardAgentHandler, AgentConfig ```