{
  "markdown": "<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"docs/logo-dark.svg\">\n  <img src=\"docs/logo.svg\" alt=\"FiGuard\" height=\"44\" />\n</picture>\n\n[![CI](https://github.com/figuard/figuard-core/actions/workflows/ci.yml/badge.svg)](https://github.com/figuard/figuard-core/actions/workflows/ci.yml)\n[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-0A5C38.svg)](LICENSE)\n[![Tests](https://img.shields.io/badge/tests-620%20passing-0A5C38)](#)\n[![PyPI](https://img.shields.io/pypi/v/figuard?color=0A5C38)](https://pypi.org/project/figuard/)\n[![npm](https://img.shields.io/npm/v/figuard?label=npm%20(ts-sdk)&color=0A5C38)](https://www.npmjs.com/package/figuard)\n[![npm](https://img.shields.io/npm/v/figuard-mcp?label=figuard-mcp&color=0A5C38)](https://www.npmjs.com/package/figuard-mcp)\n\n---\n\nA travel-booking agent hit a Stripe timeout and retried twice. The customer's card was charged **three times for the same flight** before anyone noticed — 40 minutes later.\n\nNo alert fired. No limit existed. The agent had a valid API key and no concept of \"I already did this.\"\n\nFiGuard gives agents **bounded resources** — money, tokens, API calls, GPU hours, any unit you define — and they ask permission before consuming them. You set the ceiling, the retry rules, and the idempotency policy once. Every attempt, authorized or denied, lands in an append-only audit log.\n\nThat exact failure is in the stress harness: a retried charge produces **0 double-charges**, and 100 agents racing one budget produce **0 overspends** — verified against the ledger, reproducibly (`make bench`).\n\nYour framework decides what to do next. FiGuard decides whether the resource-consuming action is allowed.\n\n```\n  Your agent code  (LangChain · LangGraph · CrewAI · any runtime)\n  orchestrates — decides what to do next\n          ↓  agent wants to spend / call / execute\n  figuard.authorize()\n  checks: limit · category · velocity · dedup\n          ↓  AUTHORIZED — action proceeds\n  Stripe · OpenAI · any API or service\n  executes — real money or resource consumed\n          ↓  action completes\n  figuard.confirm()\n  settles reservation — ledger updated\n```\n\n**LangChain / LangGraph** — FiGuard authorizes each tool call before it executes. A budget-exhausted agent stops cleanly instead of running up cost — even across parallel nodes in a LangGraph.\n\n**CrewAI** — Each crew member gets a delegation token with its own cap. A runaway specialist is stopped at its limit without affecting the rest of the crew.\n\n**OpenAI Agents SDK / MCP** — Wrap tools with `@guarded_function_tool` or add the FiGuard MCP server — every tool call is pre-flight authorized before it reaches the API.\n\n**Not using a framework?** — The raw SDK works anywhere — a Python script, a background job, a serverless function. If it calls an API that costs money or consumes a bounded resource, FiGuard fits.\n\n![FiGuard demo](https://github.com/user-attachments/assets/e953a132-c379-45fe-9796-644a4ec84c5d)\n\n**Try it now — no setup, no signup:**  \n→ `pip install figuard` — runs locally on your machine, nothing hosted ([Quickstart](#quickstart))  \n→ [Run in Colab](https://colab.research.google.com/github/figuard/figuard-notebooks/blob/main/agent-incidents/01_infinite_loop.ipynb) — or try it in the browser  \n→ [Live dashboard](https://figuard-sandbox-g1ha.onrender.com/ui)\n\n> FiGuard is the authorization and ledger layer — not a payment processor, not a policy DSL, not an adversarial-agent firewall. [Full scope →](#what-figuard-is-not)\n\n---\n\n## Quickstart\n\n**Tested with:**\n\n| Framework | Versions | Python |\n|---|---|---|\n| LangChain | ≥ 0.3.0 | 3.9 – 3.12 |\n| LangGraph | ≥ 0.2.0 | 3.10 – 3.12 |\n| CrewAI | ≥ 0.102 | 3.10 – 3.12 |\n| OpenAI Agents SDK | ≥ 0.0.5 | 3.10 – 3.12 |\n| TypeScript SDK | Node ≥ 18 | — |\n| MCP server | Claude Code, Cursor, Claude Desktop | — |\n\n```bash\npip install figuard\n```\n\n```python\nfrom figuard import FiGuardClient\n\n# Zero-config, zero-infra — runs enforcement locally (embedded SQLite, no server).\n# To share one budget across agents/processes, point at a server:\n#   FiGuardClient(api_key=\"fg_live_...\", base_url=\"https://figuard.mycompany.internal\")\nclient = FiGuardClient()\n\nbudget = client.create_budget(\n    user_id=\"agent_001\",\n    total_limit=500.00,\n    currency=\"USD\",\n    intent_context=\"travel booking session\",\n)\n\nauth = client.authorize(budget=budget, amount=270.00)\nprint(auth.decision)          # AUTHORIZED\nprint(auth.approved_quantity) # 270.0\n\n# Confirm with actual charged amount — may differ from requested (taxes, FX, discounts)\nclient.confirm(auth, 267.00)\n\n# Second spend — exceeds what's left ($500 - $267 = $233 remaining)\nauth2 = client.authorize(budget=budget, amount=350.00)\nprint(auth2.decision)       # DENIED\nprint(auth2.denial_reason)  # INSUFFICIENT_FUNDS\n```\n\nSame calls run against a self-hosted server — and there, every authorization, denial, and\nconfirmation shows up in the live spend-tree dashboard. (Embedded keeps the same ledger in\nyour local SQLite; the live dashboard is a server feature.)\n\nNot sure what limits to set? Add `trust_mode=\"SHADOW\"` to `create_budget` — all checks run, nothing is blocked, and `auth.would_have_been` tells you what would have happened. When the limits look right, switch to enforcement without recreating the budget: `client.update_budget(budget.id, trust_mode=\"FULL_ENFORCEMENT\")`.\n\n---\n\n## How It Works\n\n> **Embedded and server run the same engine.** These four operations — and all **29 structured\n> denial codes** — behave identically whether you `pip install figuard` and run **embedded**\n> (in-process, against a local SQLite file) or point the client at a **self-hosted server**.\n> Session tokens, delegation tokens, and the live spend-tree *dashboard* shown below are\n> **server-mode** features; embedded keeps the same append-only ledger in your local file and\n> exposes the tree programmatically via `get_spend_tree()`.\n\nFour operations. Everything else is detail.\n\n| Operation | What it does |\n|---|---|\n| `authorize()` | Agent asks permission — capacity reserved, nothing moved yet |\n| `confirm()` | Report what actually moved — releases the reservation |\n| `void()` | Cancel a pending authorization — reservation released |\n| `fail()` | Record a failed action — reservation released |\n\n`authorize()` reserves capacity; `confirm()` / `fail()` / `void()` then settles or releases it — every transition lands in the append-only ledger, and execution happens externally (FiGuard never sees the data or proxies the call). **In embedded mode you call `authorize`/`confirm` directly on the budget; in server mode the budget issues session tokens — and delegation tokens for fleets — but the four operations are otherwise identical.** The full lifecycle (budget → tokens → fleet delegation → ledger) is diagrammed in the [API Reference](docs/api-reference.md).\n\nThe spend tree shows the full causal chain across an orchestrator and its sub-agents:\n\n![FiGuard Spend Tree — orchestrator with confirmed and denied sub-agent events](docs/spend-tree.png)\n\n---\n\n## How the Hard Parts Are Solved\n\nThe authorize endpoint looks simple — check the balance, write a record. The parts that matter aren't obvious until you've hit them in production:\n\n**Concurrent authorization** — two agents sharing a budget can both read the same available balance, both see enough funds, and both get approved. By the time the second write lands, you're over limit. The fix is a pessimistic write lock on the budget row during authorization. Easy to know, easy to forget.\n\n**Dangling reservations** — a network timeout between the authorization write and the HTTP response leaves the agent with no event ID and the budget with a reserved amount it can't release. You need idempotency keyed to the request, not the response, so a retry finds the original authorization instead of creating a second one.\n\n**The reservation/confirmation split** — if you use a single `amountSpent` field and deduct at authorization time, two concurrent authorizations both read the same balance before either writes. The correct model is two fields: `amountReserved` (deducted at authorization) and `amountSpent` (moved from reserved at confirmation). This is the two-phase reserve-then-capture pattern that payment processors use. It's not novel — it's just usually hidden inside Stripe.\n\n**Session token security** — you need a token that scopes to exactly one budget, is returned exactly once, and is never stored in plaintext. If you store the raw token and your database is breached, every active agent session is compromised. Hash at write time, never store the raw value.\n\n**Append-only ledger** — a mutable status field on an authorization record loses history. When you need to reconstruct what happened and why a budget hit its limit — or when a finance team asks why $40K of agent spend happened last Tuesday — you want every state transition as a separate row, not an update to the previous one.\n\nThese are the same problems payment infrastructure teams solved 20 years ago. The reserve-then-confirm pattern, idempotency keyed to the request, append-only ledger — none of it is novel. FiGuard is that infrastructure applied to agent systems.\n\n---\n\n## Failure Scenarios\n\nThese are failure modes that logging and observability tools can't catch — they require enforcement at authorization time. Each has a Colab to run with no API keys needed.\n\nNotebooks live in [figuard-notebooks](https://github.com/figuard/figuard-notebooks); each runs in Colab with no API keys required.\n\n| Scenario | Framework | Failure mode | FiGuard stops it at | Colab |\n|---|---|---|---|---|\n| **Payment retry storm** | LangChain | Tool times out after Stripe charges. Retry = double charge. | Idempotency key — retry returns the same event, Stripe never called twice | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/figuard/figuard-notebooks/blob/main/framework-scenarios/01_langchain_payment_retry.ipynb) |\n| **Research cost spiral** | LangGraph | Loop runs 30 iterations on an ambiguous query. LLM controls the exit. | Budget ceiling at $0.20 — loop exits at iteration 20 | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/figuard/figuard-notebooks/blob/main/framework-scenarios/02_langgraph_research_loop.ipynb) |\n| **Fleet attribution loss** | LangGraph | Supervisor routes through 3 sub-agents. No per-agent cost caps. | Delegation token per agent — researcher capped, others unaffected | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/figuard/figuard-notebooks/blob/main/framework-scenarios/03_langgraph_supervisor_fleet.ipynb) |\n| **Parallel crew blowout** | CrewAI | Parallel crew — one member makes 25 API calls on a 5-call task | Delegation cap stops the runaway member, rest of crew completes | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/figuard/figuard-notebooks/blob/main/framework-scenarios/04_crewai_parallel_crew.ipynb) |\n| **Concurrent overspend** | Any | 10 agents share one budget. All read the same balance simultaneously. | Pessimistic lock — 5 authorized, 5 denied, $1k ceiling never exceeded | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/figuard/figuard-notebooks/blob/main/agent-incidents/03_concurrent_overspend.ipynb) |\n| **Category violation** | Any | Hotel charged to flight budget. Found at month-end. | `DENIED — NO_MATCHING_ALLOCATION` at authorization time | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/figuard/figuard-notebooks/blob/main/agent-incidents/05_category_violation.ipynb) |\n\nSource: [`examples/framework_scenarios/`](examples/framework_scenarios/) · [`examples/rogue_agent_scenarios/`](examples/rogue_agent_scenarios/)\n\n```bash\npip install figuard\npython examples/framework_scenarios/langchain_payment_retry.py      # no API keys needed\npython examples/framework_scenarios/langgraph_research_loop.py\npython examples/framework_scenarios/langgraph_supervisor_fleet.py\npython examples/framework_scenarios/crewai_parallel_crew.py\n```\n\n---\n\n## What FiGuard Is Not\n\n**Not a payment processor.** FiGuard never touches money. It authorizes the intent to spend and records the decision. The actual payment goes through your existing processor as before.\n\n**Not a policy language.** Budget limits and allocation caps are structured data, not a DSL. FiGuard matches the category an agent declares against the categories you defined — nothing more.\n\n**Not a firewall for human users.** FiGuard is purpose-built for agent-to-service authorization. The session token model assumes agents are ephemeral and untrusted by default.\n\n**Not a replacement for Stripe spending controls.** Use both if you want defense in depth. FiGuard blocks at agent decision time; Stripe blocks at payment time. Different layers.\n\n**Not a security boundary against adversarial agents.** FiGuard enforces what the agent declares. An agent that lies about its category or amount bypasses category enforcement. FiGuard is designed for honest agents with bounded resources — the same threat model as a database connection pool or a rate limiter. It prevents accidental overspend and enforces organizational policies on well-behaved agents. For adversarial agent containment, pair FiGuard with a security layer like [Microsoft AGT](https://github.com/microsoft/agt).\n\nObservability tools record what happened after execution. LLM gateways manage model routing and token spend. FiGuard is the enforcement layer — it authorizes before any action executes, across the full resource spectrum. They complement each other.\n\n---\n\n## Self-Hosting\n\n**Most teams start with embedded mode above — `pip install figuard`, zero infra.** Self-host when you need a budget shared across multiple processes or machines, delegation tokens for a fleet, or the live spend-tree dashboard. It's the graduation tier, not a prerequisite.\n\nSelf-hosting is then a single Docker container alongside your existing infrastructure — same as adding Postgres or Redis. Your spend data never leaves your environment.\n\n```bash\ngit clone https://github.com/figuard/figuard-core\ncd figuard-core\ndocker compose -f docker-compose.prod.yml up -d   # pulls the released image\n# Ready at http://localhost:8080\n```\n\n> `docker-compose.prod.yml` pulls the published `ghcr.io/figuard/figuard-core:latest` (the\n> last released version). The default `docker-compose.yml` builds from source — for contributors.\n\nPoint your client at it:\n\n```python\nclient = FiGuardClient(\n    api_key=\"your_api_key\",\n    base_url=\"http://localhost:8080\",\n)\n```\n\nFull setup guide, environment variables, Postgres configuration, and production checklist: [Self-Hosting](docs/self-hosting.md).\n\n---\n\n## Performance\n\nThe headline isn't speed — it's correctness under concurrency. The stress harness\n([`bench/stress.py`](bench/stress.py)) verifies the invariants directly against the\nPostgres ledger, not the HTTP responses:\n\n- **0 overspends** across concurrent authorizations on a shared budget — 100 agents race for a $1,000 budget, exactly 20 win, the budget lands at exactly $1,000.00, never over.\n- **0 double-charges** across retried requests — the same idempotency key fired 50× in parallel produces exactly one event.\n\nTypical authorize latency against the server (each call on its own budget, M1 / Docker):\n**p50 17ms, p99 74ms.** Under deliberate single-budget contention the pessimistic lock\nserializes requests — they queue rather than race, which is the price of never overspending.\n\nIn **embedded** mode there's no network hop and no Postgres — an authorize is an in-process\nSQLite transaction — so latency is lower still, and there's nothing to deploy.\n\nFull methodology, numbers, and reproduction in **[BENCHMARKS.md](BENCHMARKS.md)** — or run\nit yourself: `make bench`.\n\n---\n\n## Docs\n\n**Start here:**\n- [API Reference](docs/api-reference.md) — full endpoint reference with payloads\n- [Pick Your Pattern](docs/pick-your-pattern.md) — decision tree: find your scenario, get exact code\n- [Framework Integrations](docs/integrations.md) — LangChain, CrewAI, OpenAI Agents SDK, Anthropic\n- [Self-Hosting](docs/self-hosting.md) — Docker, Postgres, production checklist\n\n**Reference:**\n- [Budget Configuration](docs/budget-configuration.md) — full parameter reference for all configuration layers\n- [Enforcement Features](docs/enforcement.md) — denial codes, anomaly detection, allocation modes\n- [Fleet Agents & Delegation Tokens](docs/fleet-agents.md)\n- [Handling Denials](docs/denial-handling.md) — per-code recovery strategies, LLM prompt instructions\n- [Audit & Replay](docs/audit-replay.md) — ledger, point-in-time snapshots, timeline, what-if analysis\n- [Webhooks](docs/webhooks.md) — event types, registration, signature verification\n- [Observability](docs/integrations/observability.md) — FiGuard spans in Langfuse, Jaeger, Honeycomb, Datadog\n- [TypeScript SDK](docs/typescript-sdk.md)\n- [MCP Server](docs/integrations/mcp.md)\n- [Cookbook](docs/cookbook.md) — short recipes: authorize/confirm/void, parallel calls, causal chains, testing\n- [Known Limitations](docs/known-limitations.md)\n\nInteractive API docs: [localhost:8080/swagger-ui](http://localhost:8080/swagger-ui/index.html) · [sandbox](https://figuard-sandbox-g1ha.onrender.com/swagger-ui/index.html)\n\n---\n\n## SDKs\n\n| SDK | Install |\n|---|---|\n| Python | `pip install figuard` |\n| TypeScript / Node.js | `npm install figuard` |\n| MCP Server | `npx figuard-mcp` |\n\n---\n\n## Roadmap\n\n**Recently shipped (v1.2.0):** **embedded mode** — `pip install figuard` runs enforcement in-process against a local SQLite file, zero infra, same engine as the server; plus `update_budget()`, `get_spend_tree()` in embedded, and persistent local budgets.\n\n**Next:**\n\n- **Java SDK** — JVM client (today it's available from source under `sdk/java`; a published Maven Central artifact is planned)\n- **Scoped tokens** — derived session tokens with hard restrictions on action types, categories, and max transaction amount; for untrusted sub-agent delegation\n- **Overdraft policies** — per-budget `REJECT` / `ALLOW_IF_AVAILABLE` / `ALLOW_WITH_OVERDRAFT` modes\n\nSee [ROADMAP.md](ROADMAP.md) for the full list.\n\n---\n\n## Versioning\n\nFiGuard follows [Semantic Versioning](https://semver.org/). v1.0.0 is the first stable release — the API and SDK interfaces are stable from this version forward.\n\n---\n\n## Contributing\n\nIssues, PRs, and integration requests welcome.\n\n- [Contributing guide](CONTRIBUTING.md)\n- [Good first issues](https://github.com/figuard/figuard-core/labels/good-first-issue)\n- [GitHub Discussions](https://github.com/figuard/figuard-core/discussions)\n\nLooking for contributors on: Go SDK · LlamaIndex integration · DSPy integration · Helm chart\n\n---\n\n## License\n\nApache 2.0 — see [LICENSE](LICENSE).\n",
  "bytes": 19074,
  "sha": "11c0091f56ea7cfc2b51d5a1ecfb0b6cf6ef31cd581b310a0f112d05f7ce55c1",
  "repo_slug": "figuard/figuard-core",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_figuard_figuard_mcp_06beefdc/readme"
}