Metadata-Version: 2.5
Name: callfence
Version: 0.1.1
Summary: Test every action. Trust every agent. Open-source AI agent action testing, verification and reliability platform.
Project-URL: Homepage, https://github.com/BrayoJunior/CallFence
Project-URL: Documentation, https://github.com/BrayoJunior/CallFence#readme
Project-URL: Repository, https://github.com/BrayoJunior/CallFence
Project-URL: Issues, https://github.com/BrayoJunior/CallFence/issues
Project-URL: Changelog, https://github.com/BrayoJunior/CallFence/blob/main/RELEASE_NOTES.md
Author: CallFence Contributors
License: Apache-2.0
License-File: LICENSE
Keywords: ai-agents,llm-testing,mcp,pytest,reliability,testing,verification
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.10
Requires-Dist: pydantic>=2.7.0
Requires-Dist: pyyaml>=6.0.1
Provides-Extra: cli
Provides-Extra: dev
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0.12; extra == 'dev'
Description-Content-Type: text/markdown

# CallFence

**Test every action. Trust every agent.**

[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![GitHub Release](https://img.shields.io/github/v/release/BrayoJunior/CallFence?color=blue)](https://github.com/BrayoJunior/CallFence/releases)
[![Python Support](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14-blue.svg)](https://github.com/BrayoJunior/CallFence)
[![CI](https://github.com/BrayoJunior/CallFence/actions/workflows/ci.yml/badge.svg)](https://github.com/BrayoJunior/CallFence/actions/workflows/ci.yml)
[![Status](https://img.shields.io/badge/status-public_beta_0.1.1-orange.svg)](https://github.com/BrayoJunior/CallFence/releases)

CallFence is an open-source testing, verification, and reliability platform for tool-using AI agents. It provides a local-first, developer-friendly framework to define behavioral contracts, deterministically assert compliance in CI/CD, safely record and replay tool interactions, and mediate runtime actions with fail-closed security.

---

## The Problem CallFence Solves

AI agents that interact with external tools (databases, APIs, file systems, financial services) are inherently non-deterministic. When testing them:
- **Mocking is fragile:** Unit test mocks fail to capture multi-step ordering, schema drift, or authorization boundaries.
- **Testing in staging is dangerous and expensive:** Hitting live APIs incurs latency, costs LLM tokens, and risks unintended mutations.
- **Failures are catastrophic:** Prompt injection, hallucinated parameters, or runaway tool loops can execute unauthorized actions before anyone notices.

**CallFence solves this by sitting at the tool execution boundary:**
1. It validates actions against declarative behavioral contracts *before* functions run.
2. It blocks unauthorized tools, invalid parameters, and out-of-order calls fail-closed.
3. It deterministically records live interactions into sanitized fixtures and replays them offline with zero external network or tool calls.

---

## Architecture & Enforcement Perimeter

```
  ┌────────────────────────────────────────────────────────────────────────┐
  │                           AI AGENT REASONING                           │
  │            (LangGraph, OpenAI SDK, AutoGen, CrewAI, Custom)            │
  └───────────────────────────────────┬────────────────────────────────────┘
                                      │ Emits tool call (name, arguments)
                                      ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                    CALLFENCE CONTROLLED PERIMETER                          │
│                                                                            │
│   ┌────────────────────────────────────────────────────────────────────┐   │
│   │                      CallFenceSession / Registry                   │   │
│   │                     (@registry.tool / wrap_tool)                   │   │
│   └─────────────────────────────────┬──────────────────────────────────┘   │
│                                     │ Passes execution intent              │
│                                     ▼                                      │
│   ┌────────────────────────────────────────────────────────────────────┐   │
│   │                     Fail-Closed PolicyEngine                       │   │
│   │  - Tool Authorization (allowed / disallowed)                       │   │
│   │  - Argument Constraints (types, ranges, regex, enums)              │   │
│   │  - Sequence Rules (enforced ordering & prerequisites)              │   │
│   │  - Concurrency Budgets & Cryptographic Approval Tokens             │   │
│   └───────────────┬──────────────────────────────────┬─────────────────┘   │
│                   │                                  │                     │
│         [Blocked] │ Fail-Closed                      │ [Approved]          │
│                   ▼                                  ▼                     │
│         PolicyViolationError         ┌─────────────────────────────────┐   │
│         (0 target tool side-effects) │       ToolReplayer (Replay)     │   │
│                                      │                OR               │   │
│                                      │     Target Tool Execution (Live)│   │
│                                      └───────────────┬─────────────────┘   │
│                                                      │                     │
│                                                      ▼                     │
│                                      ┌─────────────────────────────────┐   │
│                                      │ ExecutionTrace & ToolRecorder   │   │
│                                      └─────────────────────────────────┘   │
└──────────────────────────────────────┬─────────────────────────────────────┘
                                       │
                                       ▼
    ┌──────────────────────────────────┴──────────────────────────────────┐
    │                     DEVELOPER FEEDBACK LOOPS                        │
    │  - Deterministic Behavioral Assertions (assert_called, assert_seq) │
    │  - Pytest Plugin Integration (fixtures, markers, rich diffs)        │
    │  - Standalone CLI (contract validate, recording inspect, replay)    │
    │  - Developer Reporting (ANSI terminal summaries & JSON export)      │
    └─────────────────────────────────────────────────────────────────────┘
```

> [!IMPORTANT]
> **Enforcement Boundary:** CallFence enforces policies strictly on actions dispatched through its controlled registry and session interfaces (`session.execute`, `registry.execute`, `CallFence.execute`). Direct unmediated invocations of underlying Python callables bypass this perimeter.

---

## Key Features

- **Native Pytest Integration:** Zero-configuration fixtures (`callfence_session`, `callfence_contract`, `callfence_record`, `callfence_replay`), `@pytest.mark.callfence` markers, and custom assertion failure formatting.
- **Unified Command-Line Interface (`callfence`):** Offline CLI tools to validate contracts, inspect recordings, audit traces, and verify replay fixture integrity without running target agents.
- **Developer Execution Reporting:** Rich terminal reports with ANSI status badges, execution timelines, latency breakdowns, and machine-readable JSON exports.
- **Executable Behavioral Contracts:** Declarative YAML and programmatic Pydantic schemas defining authorized tools, parameter constraints, sequence workflows, and approval thresholds.
- **Deterministic Behavioral Assertions:** Zero-token-cost, sub-millisecond assertions validating tool calls, argument values, sequence ordering, and authorization outcomes.
- **Fail-Closed Runtime Mediation:** Controlled execution boundary that enforces policy checks and validates arguments *before* real-world mutations happen.
- **Safe Fixture Recording & Replay:** VCR-for-Agents engine capturing sanitized fixtures with guaranteed zero tool side-effects during replay.
- **Local-First & Offline:** Zero external SaaS dependencies, zero required LLM API keys for testing.

---

## Installation

CallFence requires Python 3.10 or newer.

```bash
# Standard installation from PyPI:
pip install callfence

# Or install from the git repository at tag v0.1.1:
pip install "git+https://github.com/BrayoJunior/CallFence.git@v0.1.1"

# Historical GitHub v0.1.0 release baseline:
# pip install https://github.com/BrayoJunior/CallFence/releases/download/v0.1.0/callfence-0.1.0-py3-none-any.whl
```

> [!NOTE]
> *The CallFence CLI, pytest fixtures, and ANSI terminal reporting are fully self-contained in the core package and require zero external CLI or reporting dependencies.*

### Supported Python Environments
CallFence is continuously validated in clean virtual environments on **Linux (Ubuntu)** and **Windows** across:
- **Python 3.10**
- **Python 3.11**
- **Python 3.12**
- **Python 3.13**
- **Python 3.14**

---

## Quickstart

### 1. Controlled Execution & Assertions

```python
from callfence import (
    ArgumentConstraint,
    CallFenceSession,
    Contract,
    FenceToolRegistry,
    ToolPolicy,
    assert_called,
    assert_sequence,
)

# 1. Define declarative behavioral contract
contract = Contract(
    project="support-agent",
    tools={
        "lookup_user": ToolPolicy(
            allowed=True,
            constraints={"user_id": ArgumentConstraint(type="string", required=True)},
        ),
        "reset_password": ToolPolicy(allowed=True),
    },
)

# 2. Register tools with CallFence
registry = FenceToolRegistry(contract=contract)


@registry.tool(name="lookup_user")
def lookup_user(user_id: str) -> dict:
    return {"id": user_id, "email": "user@example.com"}


@registry.tool(name="reset_password")
def reset_password(user_id: str) -> dict:
    return {"status": "EMAIL_SENT"}


# 3. Execute actions through CallFence's controlled session
with CallFenceSession(contract=contract, registry=registry) as session:
    session.execute("lookup_user", user_id="USR-42")
    session.execute("reset_password", user_id="USR-42")

    # 4. Deterministically assert tool compliance
    assert_called(session, "lookup_user", times=1)
    assert_sequence(session, ["lookup_user", "reset_password"])
```

---

## Testing with Pytest

CallFence includes a native pytest plugin that automatically activates when `callfence` is installed.

### Example Pytest Suite (`test_agent.py`)

```python
import pytest
from callfence import (
    Contract,
    ToolPolicy,
    assert_called,
    assert_not_called,
    assert_sequence,
    assert_replay_complete,
)

CONTRACT = Contract(
    project="order-service",
    tools={
        "check_inventory": ToolPolicy(allowed=True),
        "charge_card": ToolPolicy(allowed=True),
        "cancel_order": ToolPolicy(allowed=False),  # Blocked by default
    },
)


@pytest.mark.callfence(contract=CONTRACT)
def test_order_flow_live(callfence_session):
    """Test agent execution under live contract enforcement."""

    # Register tools
    @callfence_session.registry.tool(name="check_inventory")
    def check_inventory(item: str) -> dict:
        return {"item": item, "in_stock": True}

    @callfence_session.registry.tool(name="charge_card")
    def charge_card(amount: float) -> dict:
        return {"status": "PAID", "amount": amount}

    # Simulate agent action
    callfence_session.execute("check_inventory", item="laptop")
    callfence_session.execute("charge_card", amount=999.0)

    # Assertions
    assert_called(callfence_session, "check_inventory", times=1)
    assert_called(callfence_session, "charge_card", times=1)
    assert_not_called(callfence_session, "cancel_order")
    assert_sequence(callfence_session, ["check_inventory", "charge_card"])


@pytest.mark.callfence(contract=CONTRACT)
def test_order_flow_replay(callfence_session, callfence_record, callfence_replay, tmp_path):
    """Record live calls once, then replay deterministically in CI."""
    fixture = tmp_path / "order_recording.json"

    # Step 1: Record live interaction
    with callfence_record(fixture):
        callfence_session.execute("check_inventory", item="laptop")

    # Step 2: Replay interaction (no real tools or external calls)
    with callfence_replay(fixture) as replayer:
        result = callfence_session.execute("check_inventory", item="laptop")
        assert result["in_stock"] is True
        assert replayer.is_exhausted

    assert_replay_complete(callfence_session)
```

Run tests with standard pytest:
```bash
pytest -v
```

See the [Pytest Integration Guide](docs/guides/testing_with_pytest.md) for full fixture reference and assertion catalogs.

---

## Command-Line Interface (CLI)

The `callfence` CLI provides standalone validation, auditing, and inspection commands:

```bash
# 1. Validate contract syntax and integrity
callfence contract validate contracts/order_flow.yaml
callfence validate contracts/order_flow.yaml --json

# 2. Inspect a recorded tool-interaction fixture
callfence recording inspect fixtures/order_run.json
callfence recording inspect fixtures/order_run.json --json

# 3. Inspect an execution trace from a past run
callfence trace inspect traces/run_01.json
callfence trace inspect traces/run_01.json --violations-only

# 4. Verify replay fixture integrity and sequence ordering
callfence replay validate fixtures/order_run.json
```

See the [CLI Reference Guide](docs/guides/cli_reference.md) for complete options and usage examples.

---

## Developer Execution Reporting

CallFence provides structured reporting to summarize agent tool activity, audit policy violations, and measure latency:

```python
from callfence.reporting import collect_report, format_terminal_report, format_json_report

# Collect metrics from a session or trace
report = collect_report(session)

# Print human-readable ANSI terminal summary
print(format_terminal_report(report))

# Export machine-readable JSON for CI artifacts
json_data = format_json_report(report)
```

---

## Explicit Security Boundaries & Limitations

CallFence is designed with transparent and honest security boundaries:

1. **Controlled Dispatch Boundary:** CallFence strictly enforces policies on actions dispatched through its controlled registry and session interfaces (`session.execute`, `registry.execute`, `CallFence.execute`).
2. **Direct Calls Bypass Enforcement:** Direct unmediated calls to underlying Python functions (e.g. `my_raw_function()`) bypass CallFence and are not intercepted.
3. **Decorators are Conveniences:** `@registry.tool` and `@wrap_tool` decorators register and wrap callables; they are not an operating-system sandbox or monkey-patch boundary.
4. **Deterministic Replay Boundary:** Replay makes recorded tool responses reproducible at the tool dispatch boundary. It does *not* make non-deterministic LLM reasoning or token generation identical across runs.
5. **No Universal Network/Filesystem Sandboxing:** Replay fixtures prevent calls to registered tool functions. They do not sandbox out-of-band network, socket, or disk operations initiated outside registered tools.
6. **Process-Local State:** Token replay guards, concurrency counters, and execution budgets are thread-safe and process-local. Distributed environments require external shared state backends.
7. **Sanitization Guarantees:** Automatic sanitization masks standard credential names (API keys, authorization headers, passwords). It cannot guarantee removal of proprietary or obfuscated secrets in arbitrary user-defined objects.
8. **Fixture Integrity vs Authenticated Integrity:** Replay fixtures use Pydantic schema validation, size/depth bounds, and canonical JSON argument representations to detect syntax corruption, truncation, and argument drift. Fixtures are standard JSON documents and do not provide authenticated cryptographic signatures; an ordinary hash or digest check detects accidental alteration or corruption, but does not prevent an adversary with local write access to the filesystem from modifying content and recomputing hashes.

---

## Realistic Agent Workflow Examples

Explore complete, runnable demonstrations in the repository:
- **[LangGraph Integration Demo](examples/langgraph_integration_demo.py):** Real-world compiled StateGraph agent using LangGraph (`langgraph==1.2.24`), routing tool execution through CallFence, enforcing policies, intercepting out-of-bounds/out-of-order tool calls fail-closed, and replaying fixtures offline.
- **[Workflow A: Financial Transaction Agent](examples/real_world_financial_agent.py):** Autonomous disbursement agent with balance checks, approval thresholds ($5,000), fail-closed destination constraints, and zero-side-effect offline replay.
- **[Workflow B: Research & Document Synthesis Agent](examples/real_world_research_agent.py):** Multi-step literature review agent with strict search-fetch-summarize pipeline sequencing, enum format constraints, and violation reporting.
- **[Framework Integration Demo](examples/framework_integration_demo.py):** Integration with generic LLM tool-calling loops (LangGraph, OpenAI SDK, Anthropic Tool Use) routing tool calls through CallFence.

---

## Running Tests and Examples

Clone the repository and run the test suite or examples:

```bash
# 1. Install development dependencies
uv sync --extra dev --extra cli

# 2. Run test suite with branch coverage enforcement (>= 90%)
uv run pytest --cov=src/callfence --cov-branch --cov-report=term-missing

# 3. Run runnable workflow examples:
uv run python examples/langgraph_integration_demo.py
uv run python examples/real_world_financial_agent.py
uv run python examples/real_world_research_agent.py
uv run python examples/record_and_replay.py
```

---

## Maturity & Release Status

**Current Version:** `0.1.1` (Public Beta — First PyPI Release)  
CallFence is currently in **Public Beta**. The core contract engine, policy enforcement boundary, recording/replay engine, pytest integration, and CLI are feature-complete and tested against a comprehensive suite with >93% branch coverage. Feedback and community contributions are welcome!

---

## Documentation & Community

- [Getting Started Guide](docs/guides/getting_started.md)
- [Behavioral Contract Format](docs/guides/contract_format.md)
- [Core Architecture & API](docs/guides/core_api.md)
- [Recording and Replay Guide](docs/guides/record_and_replay.md)
- [Testing with Pytest Guide](docs/guides/testing_with_pytest.md)
- [CLI Reference Guide](docs/guides/cli_reference.md)
- [Release Notes](RELEASE_NOTES.md)
- [Contributing Guidelines](CONTRIBUTING.md)
- [Security Policy](SECURITY.md)
- [Code of Conduct](CODE_OF_CONDUCT.md)

---

## License

Apache License 2.0. See [LICENSE](LICENSE) for details.
