CallFence
Test every action. Trust every agent.
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:
- It validates actions against declarative behavioral contracts before functions run.
- It blocks unauthorized tools, invalid parameters, and out-of-order calls fail-closed.
- 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) │
└─────────────────────────────────────────────────────────────────────┘
Key Features
- Native Pytest Integration: Zero-configuration fixtures (
callfence_session,callfence_contract,callfence_record,callfence_replay),@pytest.mark.callfencemarkers, 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.
# 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
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
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)
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:
pytest -v
See the Pytest Integration Guide for full fixture reference and assertion catalogs.
Command-Line Interface (CLI)
The callfence CLI provides standalone validation, auditing, and inspection commands:
# 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 for complete options and usage examples.
Developer Execution Reporting
CallFence provides structured reporting to summarize agent tool activity, audit policy violations, and measure latency:
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:
- Controlled Dispatch Boundary: CallFence strictly enforces policies on actions dispatched through its controlled registry and session interfaces (
session.execute,registry.execute,CallFence.execute). - Direct Calls Bypass Enforcement: Direct unmediated calls to underlying Python functions (e.g.
my_raw_function()) bypass CallFence and are not intercepted. - Decorators are Conveniences:
@registry.tooland@wrap_tooldecorators register and wrap callables; they are not an operating-system sandbox or monkey-patch boundary. - 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.
- 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.
- Process-Local State: Token replay guards, concurrency counters, and execution budgets are thread-safe and process-local. Distributed environments require external shared state backends.
- 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.
- 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: 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: 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: Multi-step literature review agent with strict search-fetch-summarize pipeline sequencing, enum format constraints, and violation reporting.
- Framework Integration Demo: 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:
# 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
- Behavioral Contract Format
- Core Architecture & API
- Recording and Replay Guide
- Testing with Pytest Guide
- CLI Reference Guide
- Release Notes
- Contributing Guidelines
- Security Policy
- Code of Conduct
License
Apache License 2.0. See LICENSE for details.
Metadata
Release files for callfence 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| callfence-0.1.1.tar.gz | 262.7 kB | With provenance | Details for callfence-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| callfence-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for callfence-0.1.1-py3-none-any.whl |
Total release size: 348.3 kB
Release files / callfence-0.1.1.tar.gz
| Download URL | callfence-0.1.1.tar.gz |
|---|---|
| Size | 262.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7cc22d9e769159c062e715c3a37596e69fc66514bbfb4d11c4a1ca386a2be8ed
|
|
BLAKE2b-256 checksum How to use checksums |
fb1626b724f54aaccf755d14ed943a8e716625a0ac9a7f8c7aecda11fbaf85c4
|
| 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 23, 2026.
Transparency logRelease files / callfence-0.1.1-py3-none-any.whl
| Download URL | callfence-0.1.1-py3-none-any.whl |
|---|---|
| Size | 85.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f7c3ffa0f756f1df5c53b38167118afbad65765c55ccbfab40997e381a74ad24
|
|
BLAKE2b-256 checksum How to use checksums |
dd2f3b5457304d53c2fb8ad0e0e27f67b2f491455d8ce133e93428e659c29a9c
|
| 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 23, 2026.
Transparency logSecurity for callfence 0.1.1
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.
Attestation for callfence-0.1.1.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 23, 2026.
Transparency logA 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.