Skip to main content

Framework-agnostic telemetry and monitoring agent for the Guard security ecosystem (fastapi-guard, flaskapi-guard, djangoapi-guard, tornadoapi-guard)

Project description

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)
  • buffer_overflow_policy: Literal["drop", "block", "raise"]: Behavior when the in-memory buffer is full (Default: "drop")
    • "drop": silently evict the oldest entry; production-safe for high-throughput, loses events when the SaaS endpoint is unreachable
    • "block": backpressure the caller until a flush frees space; appropriate when event integrity matters more than request latency
    • "raise": throw BufferFullError so callers can react; appropriate in tests or strict environments

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

guard_agent-2.4.0.tar.gz (65.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

guard_agent-2.4.0-py3-none-any.whl (29.2 kB view details)

Uploaded Python 3

File details

Details for the file guard_agent-2.4.0.tar.gz.

File metadata

  • Download URL: guard_agent-2.4.0.tar.gz
  • Upload date:
  • Size: 65.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.20

File hashes

Hashes for guard_agent-2.4.0.tar.gz
Algorithm Hash digest
SHA256 c9dccbdaa152111e906053e6ca38516f8346d85172bc67facef476b69ba47020
MD5 c0cd7c38e3125bc564e8cd8e07b65eee
BLAKE2b-256 cc08f859c34bd579043ea9cdfaa973fc4fc119601d1f4811e6067a5c51576af7

See more details on using hashes here.

File details

Details for the file guard_agent-2.4.0-py3-none-any.whl.

File metadata

  • Download URL: guard_agent-2.4.0-py3-none-any.whl
  • Upload date:
  • Size: 29.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.20

File hashes

Hashes for guard_agent-2.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 26b5e586e3070567c40bcb17bc56de2e8d715dc97cb9e8394cf964a53343d27f
MD5 c8e2d2d9ce22c2f1122742e09c82b071
BLAKE2b-256 ee48a855c0b36a6c7454033a7c029dd603ca595ce1d8e59d8676f33592588b72

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page