Skip to content

rennf93/guard-agent

Guard Agent


Guard Agent is an enterprise-grade, framework-agnostic telemetry and monitoring agent for the Guard security ecosystem. It integrates with fastapi-guard, flaskapi-guard, djangoapi-guard, and tornadoapi-guard to provide centralized security intelligence, real-time policy updates, and comprehensive event collection across any Python web framework.

PyPiVersion Release License CI CodeQL

PagesBuildDeployment DocsUpdate last-commit

Python Redis Downloads

Website · Docs · Playground · Dashboard · Discord

Framework-agnostic security telemetry for Python web apps.
Feeds the Guard dashboard with events, metrics, and dynamic rules from any supported adapter.


Renamed from fastapi-guard-agent. As of guard-agent 2.0.0, the package has been renamed to reflect its multi-framework scope. The Python import path (from guard_agent import ...) is unchanged. Existing pip install fastapi-guard-agent commands continue to work via a meta-package that transitively pulls the renamed distribution.


Documentation & Platform

  • 🌐 guard-core.com — marketing site & product overview
  • 📚 Documentation — full technical documentation
  • 🎮 Playground — try the Guard stack in-browser, no install required
  • 📊 Dashboard — real-time security events, metrics, and dynamic rules for your projects
  • 💬 Discord — community & maintainer support

Ecosystem

Guard Agent is the Python telemetry agent for the Guard ecosystem. It pairs with any framework adapter built on the shared engine. Parallel implementations of the engine and adapters exist for TypeScript (on npm) and Rust (on crates.io).

Python

Package Role PyPI
guard-core Framework-agnostic security engine PyPI
guard-agent Telemetry agent (this package) PyPI
fastapi-guard FastAPI / Starlette adapter PyPI
flaskapi-guard Flask adapter PyPI
djapi-guard Django adapter PyPI
tornadoapi-guard Tornado adapter PyPI

TypeScript / JavaScript

Published under the @guardcore npm scope. Source in the guard-core-ts monorepo. Production-ready.

Package Role npm
@guardcore/core Core engine npm
@guardcore/express Express adapter npm
@guardcore/nestjs NestJS adapter npm
@guardcore/fastify Fastify adapter npm
@guardcore/hono Hono adapter npm

Rust

Published on crates.io. 🚧 Placeholder crates — implementation in progress.

Package Role crates.io
guard-core Core engine crates.io
actix-guard-rs Actix adapter crates.io
axum-guard-rs Axum adapter crates.io
rocket-guard-rs Rocket adapter crates.io
tower-guard-rs Tower adapter crates.io

All Python adapters share the same Guard Agent runtime and dashboard — a single telemetry contract across every framework.


Key Features

  • Framework-Agnostic Core: One agent, one dashboard — works with every Guard adapter (FastAPI, Flask, Django, Tornado) through a shared wire protocol.
  • Automatic Integration: Adapters wire the agent into their middleware automatically. Enable it through the adapter's SecurityConfig — no glue code required.
  • High-Performance Architecture: Built on asynchronous I/O principles to ensure zero performance impact on your application while maintaining real-time data collection capabilities.
  • Enterprise-Grade Reliability: Implements industry-standard resilience patterns including circuit breakers, exponential backoff with jitter, and intelligent retry mechanisms to guarantee data delivery.
  • Intelligent Data Management: Features multi-tier buffering with in-memory and optional Redis persistence, ensuring zero data loss during network interruptions or application restarts.
  • Real-Time Security Updates: Supports dynamic security policy updates from the centralized management platform, enabling immediate threat response without service interruption.
  • Extensible Architecture: Designed with protocol-based abstractions, allowing seamless integration with custom transport layers, storage backends, and monitoring systems.
  • Comprehensive Security Intelligence: Captures granular security events and performance metrics, providing actionable insights for security operations and compliance requirements.

Installation

uv add guard-agent

Alternatives:

poetry add guard-agent
pip install guard-agent

The legacy name fastapi-guard-agent is still published as a meta-package that installs guard-agent transitively — existing installs keep working, but new projects should use guard-agent directly.

Optional extras:

uv add "guard-agent[redis]"    # Enable Redis-backed event buffer

Getting Started

Guard Agent is embedded by your framework's adapter — you enable it through the adapter's SecurityConfig and drive its lifecycle appropriately for that framework. Each adapter's doc page covers the exact pattern; the FastAPI pattern below is the canonical async integration.

FastAPI example

FastAPI needs a lifespan context manager to start and stop the agent on the event loop:

import os
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager

from fastapi import FastAPI
from guard import SecurityConfig, SecurityDecorator, SecurityMiddleware
from guard_agent import AgentConfig, guard_agent

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=5000,
    agent_flush_interval=2,
    enable_dynamic_rules=bool(api_key),
    dynamic_rule_interval=60,
)

agent_config = AgentConfig(
    api_key=api_key,
    endpoint=core_url,
    project_id=project_id,
    buffer_size=5000,
    flush_interval=2,
)

agent = guard_agent(agent_config) if api_key else None
guard = SecurityDecorator(security_config)


@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncGenerator[None]:
    if agent:
        await agent.start()
    yield
    if agent:
        await agent.stop()


app = FastAPI(lifespan=lifespan)
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"}

Flask is synchronous and handles start/stop internally; Tornado uses await security_middleware.initialize() / reset(); Django wires the middleware via settings. See docs/adapters for the canonical pattern per framework.

With enable_agent=True, the agent automatically:

  • Captures security violations (IP bans, rate-limit breaches, suspicious request patterns)
  • Collects performance telemetry for security operations monitoring
  • Synchronizes security policies from the centralized management platform
  • Implements intelligent buffering for optimal network utilization
  • Recovers automatically from transient network failures

Advanced Configuration

For standalone use or custom event handling, instantiate the agent directly:

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)

Configuration Parameters

Authentication & Identification

  • api_key: str (Required): Authentication key for the Guard management platform
  • project_id: str | None: Unique project identifier for data segregation and multi-tenancy support

Network Configuration

  • endpoint: str: Management platform API endpoint (Default: https://api.guard-core.com)
  • timeout: int: HTTP request timeout in seconds (Default: 30)
  • retry_attempts: int: Maximum retry attempts for failed requests (Default: 3)
  • backoff_factor: float: Exponential backoff multiplier for retry delays (Default: 1.0)

Data Management

  • buffer_size: int: Maximum events in memory buffer before automatic flush (Default: 100)
  • flush_interval: int: Automatic buffer flush interval in seconds (Default: 30)
  • max_payload_size: int: Maximum payload size in bytes before truncation (Default: 1024)

Feature Control

  • enable_metrics: bool: Enable performance metrics collection (Default: True)
  • enable_events: bool: Enable security event collection (Default: True)

Security & Privacy

  • sensitive_headers: list[str]: HTTP headers to redact from collected data (Default: ["authorization", "cookie", "x-api-key"])

Migration from fastapi-guard-agent

No code changes required. The import path was always guard_agent:

# This worked before and still works:
from guard_agent import GuardAgentHandler, AgentConfig

To switch your install command:

# Old (still works via shim)
uv add fastapi-guard-agent

# New (preferred)
uv add guard-agent

Equivalent in other package managers:

# Poetry
poetry remove fastapi-guard-agent && poetry add guard-agent

# pip (or pip-tools)
pip uninstall fastapi-guard-agent && pip install guard-agent

The legacy fastapi-guard-agent name is maintained as a meta-package pointing to guard-agent>=2.0.0,<3.0.0, so pinned environments keep resolving correctly.


Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.


License

This project is licensed under the MIT License. See the LICENSE file for details.


Author

Renzo Franceschini - rennf93@users.noreply.github.com


Acknowledgements

About

Agent for reporting to FastAPI Guard Central System

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors