Skip to main content

brrragent

brrragent is a Python package for running a synchronous model/tool loop. It provides a common entry point for several model APIs and converts MCP tools into the function-calling formats expected by those APIs.

Overview

Main components:

  • run_agent: executes model responses and tool calls until completion.
  • McpToolCaller: discovers, filters, routes, and executes tools across one or more MCP servers.
  • McpServerConfig: configures Streamable HTTP, legacy HTTP+SSE, stdio, or raw JSON-RPC compatibility connections.
  • KeyPool: selects API keys and removes rate-limited keys from rotation.

Model adapters cover OpenAI, OpenAI-compatible APIs, Google Gemini, OpenRouter, and the optional Codex OAuth backend. Structured outputs, retry handling, tool result truncation, and provider routing are handled by the package.

Installation

Install from PyPI:

uv add brrragent

Gemini support uses an optional dependency:

uv add "brrragent[gemini]"

Use uv pip install instead when installing into an existing environment.

Basic use

from brrragent import McpToolCaller, run_agent

with McpToolCaller(endpoint="https://mcp.example.com/mcp") as mcp:
    result = run_agent(
        system_prompt="Follow the request and use available tools when needed.",
        user_prompt="Return a short response.",
        model="openai/gpt-5.5",
        mcp=mcp,
    )

print(result)

Image inputs

run_agent accepts one or more images with Codex OAuth, OpenAI, OpenRouter, OpenAI-compatible providers, and Gemini:

from brrragent import ImageInput, run_agent

result = run_agent(
    system_prompt="Return a concise image description.",
    user_prompt="What is shown?",
    model="codex/gpt-5.6-luna:medium",
    images=[ImageInput.from_file("photo.jpg", detail="low")],
)

Use ImageInput(url) for remote images, ImageInput.from_base64(...) for existing Base64 data, or ImageInput.from_bytes(...) for in-memory content. Multiple images preserve their input order. Detail can be auto, low, high, or original; provider and model support still applies.

Provider credentials are read from the caller's environment. Common variables are OPENAI_API_KEY (combined with OPENAI_API_KEY_PERSONAL and OPENAI_API_KEY_CORP in the OpenAI key pool), OPENROUTER_API_KEY, GEMINI_API_KEY, FIREWORKS_API_KEY, MINIMAX_API_KEY, OPENLUX_API_KEY, and ZAI_API_KEY.

Native OpenAI-compatible prefixes fireworks/<model>, minimax/<model>, openlux/<model> (legacy yunwu/<model> falls back to YUNWU_API_KEY), and z-ai/<model> (optional ZAI_BASE_URL and ZAI_REASONING_EFFORT) route directly when their API key is set and fall back to OpenRouter otherwise.

Codex OAuth

Create brrragent-owned Codex credentials with device login:

uv run brrragent-auth login

This writes direct OAuth credentials to ~/.cache/brrragent/codex-auth.json and Codex CLI credentials to ~/.cache/brrragent/codex-home/auth.json, both with 0600 permissions. Default routing does not read shared OpenCode auth or ~/.codex/auth.json.

Override locations with BRRRAGENT_AUTH_PATH, BRRRAGENT_CODEX_HOME, or command flags. Existing callers can still use BRRRAGENT_OPENCODE_AUTH_PATH and explicit CODEX_HOME values.

Use one independently issued profile per application or worker group to avoid refresh-token rotation conflicts:

uv run brrragent-auth login --profile content-worker
BRRRAGENT_PROFILE=content-worker uv run your-application

Prefer per-call selection when one process handles multiple use cases:

from brrragent import CodexAuthConfig, run_agent

result = run_agent(
    system_prompt="Return a concise answer.",
    user_prompt="Summarize this input.",
    model="codex/gpt-5.6-luna:medium",
    codex_auth=CodexAuthConfig(profile="content-worker"),
)

Explicit paths are also supported with CodexAuthConfig(auth_path="...", codex_home="..."). Per-call selection is context-local, so concurrent use cases do not need to mutate process-wide environment variables.

Applications that coordinate OAuth refreshes and persist credentials externally can supply a synchronous access token provider instead:

def shared_access_token() -> tuple[str, str | None]:
    # The application owns coordination, refresh, and durable token persistence.
    return credential_store.get_current_access_token("content-worker")

auth = CodexAuthConfig(access_token_provider=shared_access_token)

The callback returns (access_token, account_id) with None allowed for the account ID. It runs once per Codex agent call in that call's auth context. Configured providers take precedence over local credentials. Provider failures propagate without falling back to auth files, and credential availability checks do not invoke the callback. This hook serves the HTTP OAuth backend; it does not create or synchronize credentials for a separately launched Codex CLI.

To recover when the server rejects an access token before its recorded expiry, also configure rejected_access_token_provider:

def replace_rejected_access(rejected_token: str) -> tuple[str, str | None]:
    return credential_store.get_current_access_token(
        "content-worker", rejected_access_token=rejected_token
    )

auth = CodexAuthConfig(
    access_token_provider=shared_access_token,
    rejected_access_token_provider=replace_rejected_access,
)

This callback requires access_token_provider. It receives the exact rejected access token only when opening the native Responses request fails with HTTP 401, before a stream opens. The application must coordinate refreshes, reread durable state under its lock, and adopt a peer's newer token when available instead of refreshing the rejected token again. HTTP 401 indicates rejected authentication; it does not establish that the token expired.

The callback must return a changed access token and the same account ID, including None when the original account ID was None. brrragent retries the request once, preserving its payload, timeout, and session ID. Later agent turns use the replacement token. Another HTTP 401 ends that request without another callback; returning the same token does not retry it. Callback failures, invalid credentials, and account changes are terminal, with redacted errors and no local fallback. Other HTTP statuses and errors after a stream opens do not invoke this callback.

Named profiles live under ~/.cache/brrragent/profiles/<profile>/. Run device login separately for every profile; copying an auth file also copies its rotating refresh token and does not provide isolation. BRRRAGENT_PROFILE_ROOT can move the profile directory. A named profile also takes precedence over a generic CODEX_HOME value.

Prompt caching

Keep reusable tools and system instructions before request-specific content. Use one versioned key per stable prompt without user IDs, timestamps, URLs, or prompt text:

from brrragent import PromptCacheConfig

cache = PromptCacheConfig(key="workflow:v2", ttl="1h")

Pass prompt_cache=cache to run_agent. brrragent maps it to supported cache keys, explicit breakpoints, provider affinity, and Anthropic cache controls. Gemini uses its stable system-first prefix for implicit caching. An optional on_usage callback receives normalized token and cache usage for each request.

MCP servers

One caller can combine multiple endpoints:

from brrragent import McpToolCaller

mcp = McpToolCaller(
    endpoints=[
        "https://mcp.example.com/one",
        "https://mcp.example.com/two",
    ],
    allowed_tools={"*"},
    excluded_tools={"internal_*"},
)

Use explicit server configuration to mix transports or prefix tool names:

from brrragent import McpServerConfig, McpToolCaller

mcp = McpToolCaller(
    servers=[
        McpServerConfig(
            name="remote",
            url="https://mcp.example.com/mcp",
            tool_prefix="remote_",
        ),
        McpServerConfig(
            name="local",
            transport="stdio",
            command="uvx",
            args=("example-mcp-server",),
            tool_prefix="local_",
        ),
    ]
)

transport="auto" tries Streamable HTTP, legacy HTTP+SSE, then raw JSON-RPC POST compatibility. Standard transports use MCP initialization, version negotiation, persistent sessions, and clean shutdown. Duplicate visible tool names require tool_prefix configuration.

HTTP auth objects in McpServerConfig use httpx2.Auth, matching MCP SDK v2. HTTP redirects must keep the same scheme, host, and port. Configure the final endpoint URL when a server redirects to another origin. HTTP transports use the operating system trust store; set SSL_CERT_FILE or SSL_CERT_DIR for custom certificate authorities.

BRRRAGENT_MCP_URL configures one default endpoint. BRRRAGENT_MCP_URLS accepts comma-separated endpoints. When mcp is omitted and neither variable is set, run_agent runs without MCP tools.

Tool filters accept exact names and case-sensitive shell patterns such as *_search. Exclusions apply during discovery and execution.

Public API

from brrragent import (
    AgentUsage,
    CodexAuthConfig,
    ImageDetail,
    ImageInput,
    KeyPool,
    McpServerConfig,
    McpToolCaller,
    PromptCacheConfig,
    RateLimitExhausted,
    codex_auth_context,
    get_default_caller,
    pick_env_key,
    pick_key,
    run_agent,
)

Requirements

  • Python 3.12 or newer
  • httpx>=0.27.1,<1
  • httpx2>=2.12.0,<3
  • mcp>=2.2.0,<3
  • openai>=2.45.0,<4
  • google-genai>=2.33.0,<4 and websockets>=17.4,<18 for the gemini extra

Gemini support now requires Google GenAI SDK 2.33.0 or newer so installations can use websockets 17.4, which fixes GHSA-6m5v-9gmr-5665. SDK 1.x and SDK 2.0 through 2.32 are no longer supported. Applications pinned to those versions must upgrade before installing this Gemini extra. The extra also requires httpx 0.28.1 or newer through the SDK; the core package continues to support httpx 0.27.1. SDK 2.x and 3.x use the explicit Gemini v1beta API for the model and tool-calling contract.

The core HTTPX2 and MCP minimums also increase to 2.12.0 and 2.2.0, respectively, to exclude known transport and MCP security vulnerabilities. Applications pinned below these versions must upgrade their constraints. MCP 2.2 also rejects cross-origin redirects and external tool-output schema references instead of forwarding credentials or fetching remote schemas.

License

MIT

Metadata

Release files for brrragent 0.5.12

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for brrragent 0.5.12
File Size Uploaded Provenance Actions
brrragent-0.5.12.tar.gz 75.5 kB With provenance Details for brrragent-0.5.12.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for brrragent 0.5.12
File Interpreter ABI Platform Actions
brrragent-0.5.12-py3-none-any.whl Python 3 none any Details for brrragent-0.5.12-py3-none-any.whl

Total release size: 124.2 kB

Release files / brrragent-0.5.12.tar.gz

Download URL brrragent-0.5.12.tar.gz
Size 75.5 kB
Tags Source
SHA-256 checksum
How to use checksums
9c07e7c71245e8d478e52259d923b2ad9de1d6eb8bea41afe0557933696e1c41
BLAKE2b-256 checksum
How to use checksums
8fb58ed8f74442c413759688969a0a1ea9987ee689672ee98e71e6d335b6802c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Release files / brrragent-0.5.12-py3-none-any.whl

Download URL brrragent-0.5.12-py3-none-any.whl
Size 48.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d3bea44e580156842281a649e714b0375daf2425f0c5c5e389b248fae1301512
BLAKE2b-256 checksum
How to use checksums
eaddea6f0aedbdcaa35a871b22c71dfb1f1888ef6affe91e76938b1b457b2002
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Security for brrragent 0.5.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for brrragent-0.5.12.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page