Skip to main content

Contract4Agents

Contract4Agents banner

Contract4Agents is a free, open-source, typed contract language for building agent systems that are reviewable before they run and accountable afterward. The contract is the source of truth for agents, shared capabilities, authorization, composition, controls, quality criteria, and expected evidence. Target bindings supply only the framework-specific implementation details.

The product loop is:

Declare -> Compile -> Plan -> Materialize -> Run -> Trace -> Assure

That separation is the point. You can change a model, provider profile, or tool implementation without rewriting the portable agent design. Before execution, the plan shows exactly how the selected target will implement each requested semantic and blocks required guarantees it cannot honestly enforce. After execution, contract-bound traces and assurance results distinguish passed, violated, and unverified instead of treating missing evidence as success.

Quickstart

Install the core package with the target adapters your application uses:

pdm add "contract4agents[openai]"
pdm add "contract4agents[strands]"
pdm add "contract4agents[google-adk]"

To explore this repository's complete Incident Command example:

pdm install
pdm run python examples/incident-command/data/seed.py
pdm run contract4agents check examples/incident-command
pdm run contract4agents compile examples/incident-command --out .contract/build/incident-command
pdm run contract4agents plan examples/incident-command --target openai --profile test

The first two commands need no provider credentials and do not import or call application implementations. plan loads target bindings only far enough to validate coverage and safely inspect callable signatures; it does not construct agents or execute business code.

Rich Editor Support

The repo-owned VS Code extension combines the complete TextMate grammar with the same Python parser and semantic model used by the CLI. In .contract and .eval files it provides hover help, contextual completion, diagnostics and quick fixes, definition and reference navigation, rename, symbols, semantic highlighting, and optional inlay hints. Type and callable hovers show their declared shape, while contract vocabulary such as grant settings explains the meaning of each accepted value.

A Small Contract-First Team

Define portable types and a shared capability:

type SupportRequest:
    ticket_id: string
    question: string

type SupportReply:
    answer: string
    needs_follow_up: boolean

tool knowledge.search(query: string) -> SupportReply:
    description = "Search the approved support knowledge base."
    side_effect = false

Grant the capability to an agent. Availability, authorization, and execution are independent and explicit:

agent SupportResponder(request: SupportRequest) -> SupportReply:
    use knowledge.search:
        availability = enabled
        authorization = preapproved
        execution = host

    goal = "Answer the support request accurately."
    description = "Handles first-line support questions."
    guidance = [
        "Use only evidence returned by approved capabilities.",
        "Say when the available evidence is insufficient.",
    ]

Bind the portable name to one target implementation in contract4agents.targets.toml:

schema_version = "1"

[targets.openai]
adapter = "openai"

[targets.openai.tools."knowledge.search"]
python = "your_app.tools:search_knowledge"

[targets.openai.profiles.test]
default_model = "test-model"

[targets.openai.profiles.production]
default_model = "gpt-5.2"

Every target declares at least one named profile. Each profile is complete: a default_model or explicit per-agent model selects a model for every canonical agent, and stale agent overrides are rejected. The binding does not repeat prompts, permissions, schemas, agent factories, or controls. Those remain contract-owned.

Inspect Before Construction

Compile provider-neutral artifacts and review the resolved target plan:

contract4agents check agent_contracts
contract4agents compile agent_contracts --out .contract/build
contract4agents plan agent_contracts --target openai --profile production \
  --out .contract/build/production-plan.json

check remains provider-neutral when no target-binding file exists. When the file is present, it also validates every declared target and named profile. Compilation produces deterministic canonical IR, its digest, JSON Schemas, audience-safe instructions, and reviewer documentation. compile --check makes stale review artifacts a CI failure. Run generate separately with an explicit python or typescript target only when application code imports generated source; use the same target selection with generate --check.

The plan resolves models, bindings, grants, approvals, composition, controls, isolation mechanisms, host obligations, and expected event types. Each mapping is reported as exact, host_enforced, emulated, degraded, or unsupported. Required degraded or unsupported guarantees fail closed.

Materialize Normal Framework Objects

Contract4Agents constructs the complete native agent graph at runtime:

from agents import Runner
from contract4agents import materialize

result = materialize(
    "agent_contracts",
    target="openai",
    profile="production",
)

support_agent = result.agents["SupportResponder"]
reviewed_plan = result.plan
run_result = await Runner.run(support_agent, input="Where is my order?")

result.agents contains ordinary native SDK agent objects. Generated output types, host tools, approval hooks, and supported composition are wired from the contract graph and target bindings; host code does not maintain a parallel agent registry.

Portable string lengths and numeric ranges are enforced in compiler JSON Schema, generated validators, and native tool schemas. Materialization reads back final native configuration and schemas and returns conformance evidence in result.graph.validation. Generated output types enforce contract structure; application domain validation remains a post-SDK host step.

The host still owns credentials, approval decisions and UI, persistence, sessions, retries, external services, deployment, and deterministic application workflow. Contract4Agents is not a general workflow language and does not hide provider differences.

The built-in targets deliberately report different mappings:

Target Native graph Python tools/context Approval Provider-native search
OpenAI Agents SDK Agent, function tools, handoffs exact exact for Python tools OpenAI web search
Strands Agents Agent, typed tools, agents-as-tools exact exact through HumanInTheLoop Unsupported; use an ordinary Python tool
Google ADK LlmAgent, custom BaseTool, typed sub-branches exact exact through tool confirmation Schema-checked Google Search wrapper

Each target reference lists contextual exact, host_enforced, emulated, degraded, and unsupported outcomes. Neither Strands nor ADK substitutes a similar-looking SDK transfer for a contract handoff when history semantics do not match.

Evidence, Evals, and Assurance

The normalized trace schema binds every event to a contract digest, plan digest, stable semantic IDs, provider-native correlation, provenance, and audience-safe redaction metadata. Identity-bound closure evidence records which attempts, provider responses, and instrumentation channels were completely observed at an exact ordered trace frontier. Built-in adapter sessions expose consistent non-closing snapshots, validated cross-session retry continuation, and disposable router bindings. The same control assessor is used for controlled evals and imported production traces.

Run specs have a separate post-run assessor for host-supplied stage outputs, derived values, cardinality, assertions, and explicit workflow-completeness evidence. Controls and run specs remain distinct assurance results. Retried invocations can carry portable attempt identity and an explicit selected terminal attempt without moving retry or recovery decisions out of host code.

.eval files name scenarios and expectations. The target/profile eval replay workflow assesses supplied evidence without invoking the planned graph. It derives its agent, capability, grant, control, and event-type inventory from the contract and plan; users do not restate the runtime in a fixture manifest. Repeated replay campaigns report pass, violation, and unverified rates with uncertainty, latency and cost summaries, thresholds, and optional baseline comparisons.

Assurance bundles join the canonical contract, materialization plan, materialized configuration and schema conformance, normalized traces, trace closure, control results, eval summaries, and semantic diffs into one portable review package. Missing or incomplete evidence remains explicitly unverified. This is useful evidence for compliance and release review; it is not a legal certification by itself.

Public Examples

  • Incident Command is the recommended first read. It demonstrates shared capabilities, different authorization grants, explicit context origins, generated delegations, controls, target bindings, and deterministic eval data.
  • Multi-Lens Research demonstrates a larger delegation graph, typed workflow boundaries, and an explicit isolation profile.
  • Market Research Brief demonstrates host tools alongside a provider-native web-search binding.

See the examples guide for the common project structure.

Documentation

The semantic model is the detailed architecture specification. Coding agents should begin with AGENTS.md.

Development

pdm install
pdm run docs-check
pdm run validate
pdm build

Normal local checks do not require provider credentials. Opt-in provider live checks are documented in Validation and Quality Gates.

License

MIT. See LICENSE.

Metadata

Release files for contract4agents 0.16.0

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

Source distribution (sdist)

Source distribution for contract4agents 0.16.0
File Size Uploaded
contract4agents-0.16.0.tar.gz 253.9 kB Details

Built distribution (wheel)

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

Total release size: 571.2 kB

Release files / contract4agents-0.16.0.tar.gz

Download URL contract4agents-0.16.0.tar.gz
Size 253.9 kB
Tags Source
SHA-256 checksum
How to use checksums
1e6c28d117a437c6ba999709682a97dff8ba57d6c68e243c7178e8c0a761a6dc
BLAKE2b-256 checksum
How to use checksums
e2f43e7262dd706f8dc67c23682c025bbfff3af9edbbcf1aa83cc48dc3888a43
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Aug 29, 2026.

Transparency log

Release files / contract4agents-0.16.0-py3-none-any.whl

Download URL contract4agents-0.16.0-py3-none-any.whl
Size 317.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
93590a61f43b254a53de108557654e900242dfe65c3953dab718ff194cea6ef5
BLAKE2b-256 checksum
How to use checksums
2c4a4f79a824e4bae06b76cda5e60a980fe796812149448631626c8ab422397a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Aug 29, 2026.

Transparency log

Release history Release notifications | RSS feed

0.19.0

2 release files

0.18.0

2 release files

0.17.1

2 release files

0.17.0

2 release files

This release

0.16.0 This release

2 release files

0.15.1

2 release files

0.15.0

2 release files

0.14.0

2 release files

0.13.0

2 release files

0.12.2

2 release files

0.12.1

2 release files

0.12.0

2 release files

0.11.0

2 release files

0.10.0

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.0

2 release files

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