Metadata-Version: 2.5
Name: vectorguard-agentproof
Version: 1.1.1
Summary: Agent identity: verify which AI agent is calling and which human or business is accountable, using verifiable credentials and signed HTTP requests
Project-URL: Homepage, https://agentproof.vectorguardlabs.com
Project-URL: Documentation, https://agentproof.vectorguardlabs.com/docs
Project-URL: Repository, https://github.com/VectorGuard-Labs/AgentProof
Project-URL: Issues, https://github.com/VectorGuard-Labs/AgentProof/issues
Project-URL: Changelog, https://github.com/VectorGuard-Labs/AgentProof/releases
Project-URL: PyPI, https://pypi.org/project/vectorguard-agentproof/
Author-email: Pavon Dunbar <pavon@vectorguardlabs.com>
License-Expression: MIT
License-File: LICENSE
Keywords: agent-identity,ai-agents,aml,attestation,blockchain,credential-issuance,credential-verification,decentralized-identity,delegation,did,http-message-signatures,jwt,kyc,sd-jwt,selective-disclosure,trust-registry,verifiable-credentials,w3c
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.13
Requires-Dist: click==8.3.3
Requires-Dist: cryptography==50.0.2
Requires-Dist: fastapi==0.136.1
Requires-Dist: httpx==0.28.1
Requires-Dist: multiformats==0.3.1.post4
Requires-Dist: prometheus-client==0.22.1
Requires-Dist: pycryptodomex==3.23.0
Requires-Dist: pydantic==2.13.3
Requires-Dist: pyjwt[crypto]==2.15.1
Requires-Dist: redis[hiredis]==5.2.1
Requires-Dist: stripe==11.4.1
Requires-Dist: uvicorn==0.46.0
Provides-Extra: dev
Requires-Dist: hypothesis==6.155.1; extra == 'dev'
Requires-Dist: mutmut==3.5.0; extra == 'dev'
Requires-Dist: pip-audit==2.10.1; extra == 'dev'
Requires-Dist: pytest-asyncio==1.3.0; extra == 'dev'
Requires-Dist: pytest-cov==7.1.0; extra == 'dev'
Requires-Dist: pytest==9.2.0; extra == 'dev'
Requires-Dist: ruff==0.15.12; extra == 'dev'
Requires-Dist: ty==0.0.49; extra == 'dev'
Provides-Extra: evm
Requires-Dist: web3==7.6.0; extra == 'evm'
Provides-Extra: loadtest
Requires-Dist: locust==2.32.4; extra == 'loadtest'
Provides-Extra: pg
Requires-Dist: alembic==1.15.2; extra == 'pg'
Requires-Dist: psycopg[binary,pool]==3.2.6; extra == 'pg'
Requires-Dist: sqlalchemy==2.0.41; extra == 'pg'
Provides-Extra: tracing
Requires-Dist: opentelemetry-api==1.33.0; extra == 'tracing'
Requires-Dist: opentelemetry-exporter-otlp==1.33.0; extra == 'tracing'
Requires-Dist: opentelemetry-instrumentation-fastapi==0.54b0; extra == 'tracing'
Requires-Dist: opentelemetry-instrumentation-httpx==0.54b0; extra == 'tracing'
Requires-Dist: opentelemetry-sdk==1.33.0; extra == 'tracing'
Description-Content-Type: text/markdown

# AgentProof: Identity, Authority and Spend Control for AI Agents

[![PyPI version](https://img.shields.io/pypi/v/vectorguard-agentproof)](https://pypi.org/project/vectorguard-agentproof/)
[![Python 3.13+](https://img.shields.io/badge/python-3.13%2B-blue)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

AgentProof lets a business delegate real authority, including money, to an AI agent,
and lets every merchant or API the agent calls check that authority before acting.

It answers four questions on every request:

1. **Who is this agent, and who is accountable for it?** The agent signs each HTTP
   request with its own key. AgentProof ties that key to a registered agent and to the
   organization that owns it.
2. **What may it do?** The owner signs a delegation that limits scopes, merchants,
   expiry and spending. Sub-agents can only narrow it.
3. **May it spend this much, here, now?** The purchase is reserved against every
   budget in the delegation chain in one PostgreSQL transaction, or refused.
4. **Can this be proven later?** Every decision returns a signed receipt. Every
   committed money movement is mirrored to VectorLedger as tamper-evident evidence,
   and every security event goes on a hash-chained log with external checkpoints.

Revoking an agent or a delegation takes effect on the next request.

```
  owner (business)                     agent                             merchant / API
  ────────────────                     ─────                             ──────────────
  registers agent ───────────────▶  holds its own key
  delegates $5,000/day ───────────▶  signs every request ─────────────▶ POST /api/v1/verify-agent
  (scopes, merchants, expiry)        (RFC 9421)                          identity + delegation +
                                                                          revocation + budget
  revokes agent ──────────────────────────────────────────────────────▶ next request: DENY
                                                                          receipt, ledger, events
```

**Status.** AgentProof is a pilot candidate, not yet a production-certified financial
authorization service. The architecture, spend enforcement, recovery drills and
evidence pipeline are tested (see [Testing](#testing-and-ci)), but an independent
security review and a design-partner deployment are still to come. See
[Project status](#project-status).

---

## Contents

- [How it works](#how-it-works)
- [Quick start](#quick-start)
- [Walkthrough: an agent makes a purchase](#walkthrough-an-agent-makes-a-purchase)
- [OAuth and MCP](#oauth-and-mcp)
- [Evidence and accountability](#evidence-and-accountability)
- [Security model](#security-model)
- [Running in production](#running-in-production)
- [API overview](#api-overview)
- [The credential layer underneath](#the-credential-layer-underneath)
- [Testing and CI](#testing-and-ci)
- [Project status](#project-status)
- [Documentation](#documentation)

---

## How it works

| Component | Role |
|---|---|
| **AgentProof API** (`agentproof-server`, FastAPI) | Agent registry, delegations, `/verify-agent`, spend lifecycle, OAuth authorization server, receipts, event log. |
| **PostgreSQL** | **Source of truth.** Authorization and spending enforcement: every reserve, capture, release, refund and expiry is one transaction holding the state change and every budget move. |
| **VectorLedger** (optional) | **Evidence, not enforcement.** A transactional outbox in PostgreSQL feeds every committed move into VectorLedger's hash-chained ledger, at least once, with reconciliation. Never on the request path. |
| **PyHSM** (optional, recommended) | Holds the platform root key. It certifies short-lived receipt-signing keys, so receipts don't wait on the HSM. |
| **Redis** | Replay cache, single-use challenges, rate limits across instances. |
| **Checkpoint sinks** | Signed heads of the event chains, stored outside the database's control, so a privileged rewrite of history is detectable. |

PostgreSQL is the supported production database. YugabyteDB is experimental.

Design notes: [spend operations](docs/OPERATIONS_SPEND.md),
[OAuth design](docs/design/oauth-authorization.md),
[receipt signing keys](docs/design/receipt-signing-keys.md).

---

## Quick start

```bash
pip install vectorguard-agentproof            # or: pip install -e ".[dev,pg]" from a checkout
```

Run the full agent-commerce scenario in one process, with real cryptography (Ed25519
keys, signed credentials, RFC 9421 signatures, signed receipts):

```bash
python scripts/demo_agent_commerce.py                                # in-memory ledger
python scripts/demo_agent_commerce.py --database postgresql://...    # PostgreSQL enforcement
python scripts/demo_agent_commerce.py --database postgresql://... \
    --vectorledger 127.0.0.1:5433 --vl-user admin --vl-password-file ./vl-password
```

It registers a purchasing agent for Acme, grants it $5,000/day ($1,500 per purchase,
$2,000/day at one merchant), buys from two merchants, is refused when it exceeds its
authority, is revoked, and then verifies the evidence.

Run the API locally:

```bash
agentproof_ENV=development agentproof-server       # http://localhost:8000
curl http://localhost:8000/api/v1/health
```

With a database, set `agentproof_DATABASE_URL` and run `alembic upgrade head` first.

---

## Walkthrough: an agent makes a purchase

The full version, with every option, is the
[Agent Identity guide](docs/guides/agent-identity.md).

### 1. The owner registers the agent

The agent generates its own Ed25519 key; AgentProof never sees the private key. The
agent proves possession by signing a challenge addressed to the owner:

```python
from agentproof.holder import build_presentation

# POST /api/v1/agents/challenge  (owner's admin key)  -> {"nonce", "audience": owner_did}
proof = build_presentation(agent_did, [], agent_keypair,
                           audience=owner_did, nonce=nonce).proof.jwt
# POST /api/v1/agents  (owner's admin key)
# {"did": agent_did, "hosted": true, "name": "Purchasing", "agentId": "buyer-001",
#  "ownerDomain": "acme.com", "challenge": nonce, "proof": proof}
```

The response holds the registry record and a platform-signed registration credential.
With `hosted: true` the agent gets a `did:web` identity whose keys can be rotated
without changing the agent.

### 2. The owner delegates authority

```bash
curl -X POST $API/api/v1/agents/$AGENT_DID/delegations -H "X-API-Key: $OWNER_KEY" -d '{
  "scopes": ["commerce:buy"],
  "expiresInSeconds": 86400,
  "maxDepth": 1,
  "spendLimit": {"amount": "5000", "currency": "USD", "period": "day",
                 "maxPerTransaction": "1500",
                 "merchantLimits": [{"merchantDid": "did:web:books.example", "amount": "2000"}]},
  "audiences": ["shop.example.com", "books.example"]
}'
```

A sub-delegation can only narrow scopes, limits, audiences and expiry. Every link
with a limit is charged: if Acme gives agent A $10,000/day and A gives B and C
$7,000/day each, B and C together can never spend more than $10,000 a day.

### 3. The agent signs its requests

```python
import httpx
from agentproof.agent_client import AgentAuth, AgentSigner

signer = AgentSigner(agent_did, agent_keypair,
                     credentials=[registration_jwt, delegation_jwt],
                     key_id=f"{agent_did}#key-1")
async with httpx.AsyncClient(auth=AgentAuth(signer)) as client:
    await client.post("https://shop.example.com/checkout", json={"sku": "abc"})
```

Signatures follow RFC 9421 (Ed25519) and cover the method, host, path, query and body
digest, with a nonce and an expiry of at most 5 minutes.

### 4. The merchant verifies and reserves funds

A merchant authenticates with an API key bound to a DID that is linked to its domain.
It forwards the signed request, plus the purchase, to AgentProof:

```bash
curl -X POST $API/api/v1/verify-agent -H "X-API-Key: $MERCHANT_KEY" -d '{
  "method": "POST", "authority": "shop.example.com", "path": "/checkout",
  "signatureInput": "...", "signature": "...", "credentials": "...",
  "requiredScopes": ["commerce:buy"], "requireRegistered": true,
  "spend": {"amount": "1200.00", "currency": "USD", "reference": "order-8812"}
}'
```

The response says `ALLOW` or `DENY` with a reason, names the agent, its owner and
the delegation used, and includes the reservation and a signed receipt. If any budget
in the chain is short, nothing is held. Or use the middleware:

```python
from agentproof.agent_remote import RemoteAgentVerifier
from agentproof.merchant import AgentIdentityMiddleware

app.add_middleware(AgentIdentityMiddleware,
                   verifier=RemoteAgentVerifier("https://agentproof.vectorguardlabs.com",
                                                merchant_api_key,
                                                required_scopes=["commerce:buy"],
                                                require_registered=True))
```

### 5. Capture, release or refund

| Call | Effect |
|---|---|
| `POST /api/v1/spend/reservations/{id}/capture` | Take the money; `"final": false` for split shipments. Re-checks revocation first. |
| `POST /api/v1/spend/reservations/{id}/release` | Return the hold for an abandoned order. |
| `POST /api/v1/spend/reservations/{id}/refund` | Return captured money to the budgets. |

Unused holds expire (15 minutes by default) and a background worker returns them.
Every call is idempotent by reference.

### 6. Verify a receipt offline

```python
from agentproof.receipts import verify_receipt

body = await verify_receipt(receipt_jwt, resolver, trusted_issuers=[platform_did],
                            context=my_merchant_did)
```

### 7. The owner revokes the agent

```bash
curl -X PATCH $API/api/v1/agents/$AGENT_DID/status -H "X-API-Key: $OWNER_KEY" \
     -d '{"status": "REVOKED"}'
```

The next `/verify-agent` call is denied, outstanding reservations can no longer be
captured, and OAuth tokens stop being accepted at introspection.

### Or build the agent in AgentProof

A company can also design the agent itself in AgentProof: its purpose, instructions,
AI model (OpenAI or Anthropic, on the company's own account), tools and spending rules.
AgentProof produces a package the company runs on its own infrastructure. On first
start the agent generates its key where it runs and enrolls with a one-time token; it
is registered and receives its delegation automatically. The agent's key and the
company's AI-provider key never reach AgentProof. See the
[Agent Builder guide](docs/guides/agent-builder.md).

---

## OAuth and MCP

AgentProof is also an OAuth 2.1 authorization server, so MCP servers and APIs that
accept OAuth tokens can accept AgentProof agents without the SDK:

- `client_credentials` with `private_key_jwt` and mandatory DPoP. The agent's DID is
  its client id.
- Tokens are RFC 9068 JWTs: 5 minutes, one audience, DPoP-bound, no refresh tokens,
  and scopes never wider than the verified delegation.
- Endpoints: `/.well-known/oauth-authorization-server`, `/oauth/token`,
  `/oauth/introspect`, `/oauth/revoke`, `/oauth/jwks`.
- MCP tool-level scopes (`agentproof.mcp`): a delegation can grant
  `mcp:tool:search` without granting other tools.

Tokens carry identity and scopes only. Spending always goes through a reservation.

---

## Evidence and accountability

- **Signed receipts** for every decision. With delegation enabled
  (`agentproof_RECEIPT_KEY_DELEGATION=1`), the PyHSM root key certifies short-lived
  per-tenant keys. Measured with a local PyHSM: 197 purchases/s against 33/s when the
  HSM signs every receipt, with one HSM signature for 600 purchases
  ([benchmarks](docs/BENCHMARKS.md)). Keys rotate automatically and can be revoked
  across all instances (`POST /api/v1/platform/signing-keys/revoke`).
- **Objective event log**: denials, replays, revocations, spend transitions and admin
  reads. One hash chain per agent, append-only in the database, exportable as a signed
  bundle that verifies offline (`GET /api/v1/agents/{did}/events/export`).
- **External checkpoints**: the platform key signs the chain heads at intervals and
  writes them to storage outside the database (`agentproof_CHECKPOINT_FILE`, several
  paths for independent copies). A rewritten chain, or a rolled-back checkpoint log,
  is then detected.
- **VectorLedger mirror**: every committed money movement, delivered at least once
  through the outbox and reconciled hourly. `GET /api/v1/spend/evidence-status` shows
  whether the evidence is in sync, how far behind it is, and when it was last
  reconciled. A purchase is valid once PostgreSQL commits it, whatever the mirror's
  state.

---

## Security model

Full list of claims, where each is enforced, the test that backs it, and known
limitations: [docs/SECURITY_REVIEW_PACKAGE.md](docs/SECURITY_REVIEW_PACKAGE.md).

Main properties:

- No overspend across a delegation chain, under concurrency and across instances
  (PostgreSQL row locks and `CHECK` constraints; tested with concurrent children and
  grandchildren and a property-based state machine).
- Each spend operation is all or nothing, including when the process is killed
  mid-transaction.
- Only `/verify-agent` takes budget; OAuth tokens carry no spend authority.
- Replay protection on signed requests and DPoP proofs; single-use challenges.
- Tenant isolation of events, receipts and receipt-signing keys.
- The application database role cannot alter evidence or un-revoke a receipt key.
- The root key stays in PyHSM; receipt keys are never written to disk.

Report vulnerabilities privately to VectorGuard Labs (not in public issues).

---

## Running in production

| Concern | What to set or run |
|---|---|
| Database | `agentproof_DATABASE_URL` (PostgreSQL 16, TLS). Run `alembic upgrade head` before deploying. Roles: `scripts/db_roles.sql`. |
| Platform key | `agentproof_PYHSM_SOCKET`, `agentproof_PYHSM_SECRET_FILE`, `agentproof_PLATFORM_PYHSM_KEY` (or `agentproof_PLATFORM_SIGNING_KEY` without an HSM). |
| Receipt keys | `agentproof_RECEIPT_KEY_DELEGATION=1`; see [receipt-signing-keys.md](docs/design/receipt-signing-keys.md). |
| Redis | `agentproof_REDIS_URL` (required outside development: replay cache and challenges fail closed without it). |
| Evidence | `agentproof_VLEDGER_URL`, `agentproof_VLEDGER_USER`, `agentproof_VLEDGER_PASSWORD`; `agentproof_CHECKPOINT_FILE`. |
| Audit log | `agentproof_AUDIT_HMAC_SECRET`. |
| Backups | Encrypted base backups and WAL archive: `scripts/pg-backup.sh`, `scripts/pg-wal-archive.sh`, `scripts/pg-restore.sh` ([DATABASE_HARDENING.md](docs/DATABASE_HARDENING.md)). |
| Failover | Synchronous standby; drill in `scripts/pg_failover_drill.sh` (no acknowledged purchase lost). |
| Monitoring | Prometheus metrics and alert rules in `monitoring/alerts.yml`; runbook in [OPERATIONS_SPEND.md](docs/OPERATIONS_SPEND.md). |

`docker compose up` starts a development stack (API, YugabyteDB, Redis, Prometheus,
Grafana, Jaeger, Caddy). It uses YugabyteDB, which is experimental for AgentProof;
use PostgreSQL for anything beyond local testing. Secrets handling:
[SECRET_MANAGEMENT.md](docs/SECRET_MANAGEMENT.md).

---

## API overview

| Endpoint | Who | Purpose |
|---|---|---|
| `POST /api/v1/agents/challenge`, `POST /api/v1/agents` | owner | Register an agent |
| `POST /api/v1/agents/{did}/delegations` | owner | Delegate authority |
| `PATCH /api/v1/agents/{did}/status` | owner | Suspend, reactivate or revoke |
| `POST /api/v1/agents/{did}/keys`, `.../keys/{kid}/revoke` | owner | Rotate or revoke agent keys |
| `GET /api/v1/agents/{handle}/did.json` | anyone | Hosted agent DID document |
| `POST /api/v1/agent-blueprints`, `GET`/`PUT`/`DELETE .../{id}` | owner | Design agents (agent builder) |
| `POST /api/v1/agent-blueprints/{id}/enrollments`, `.../package` | owner | One-time enrollment tokens; downloadable agent package |
| `POST /api/v1/enrollment/challenge`, `/complete` | agent (enrollment token) | Agent enrolls with its own key |
| `POST /api/v1/verify-agent` | merchant | Verify a signed request; optionally reserve spend |
| `POST /api/v1/agent/challenge` | merchant | Single-use challenge for high-value actions |
| `POST /api/v1/spend/reservations/{id}/capture` \| `release` \| `refund` | merchant | Spend lifecycle |
| `GET /api/v1/spend/evidence-status` | any key | Evidence mirror status |
| `POST /api/v1/merchants/domain-link`, `.../verify` | merchant | Bind the merchant DID to its domain |
| `POST /api/v1/principals/{did}/domain-link`, `.../verify` | owner | Prove control of the owner's domain |
| `POST /api/v1/merchants/disputes` | merchant | Record a dispute as a fact |
| `GET /api/v1/agents/{did}/events`, `.../events/export` | owner | Event log and signed export |
| `GET /api/v1/platform/did.json`, `.../signing-key-revocations` | anyone | Platform keys and revoked receipt keys |
| `POST /api/v1/platform/signing-keys/revoke` | platform admin | Revoke receipt keys |
| `/oauth/*`, `/.well-known/oauth-authorization-server` | agents, resource servers | OAuth 2.1 |
| `GET /api/v1/health`, `/api/v1/health/workers` | monitoring | Health and worker state |

Full request and response details: [API-Docs.md](API-Docs.md).

---

## The credential layer underneath

AgentProof's registration and delegation credentials are W3C verifiable credentials.
The same layer provides `did:key`, `did:web` and `did:ethr` resolution, an issuer trust
registry with tiers, StatusList2021 revocation, optional on-chain attestation
anchoring (`contracts/AttestationRegistry.sol`), SD-JWT selective disclosure, billing,
and example KYC, AML and accredited-investor credential types that can back a
verified organization.

That layer and its CLI (`agentproof issue`, `agentproof verify`, ...) are documented in
[docs/CREDENTIAL_LAYER.md](docs/CREDENTIAL_LAYER.md) and [API-Docs.md](API-Docs.md).

---

## Testing and CI

```bash
pip install -e ".[dev,pg]"
pytest -q                                           # without a database: DB tests skip
export agentproof_TEST_DATABASE_URL=postgresql://user@localhost/agentproof_test
pytest -q                                           # everything (about 1 minute)
pytest -m security -q                               # release-blocking adversarial tests
PYTHON=python scripts/pg_recovery_drill.sh          # encrypted point-in-time recovery
PYTHON=python scripts/pg_failover_drill.sh          # synchronous standby failover
```

CI (`.github/workflows/ci.yml`) runs lint and type checks against recorded baselines
(no new findings allowed), a dependency audit, the security suite, the whole suite on
PostgreSQL 16 with a coverage floor, migration upgrade and rollback, and both drills.
YugabyteDB runs as a non-blocking experimental job. Policy and baselines:
[TESTING_POLICY.md](docs/TESTING_POLICY.md).

---

## Project status

Done and tested: agent registry and delegation chains, hierarchical spend limits,
atomic spend operations, the expiry worker, the evidence outbox and reconciliation,
signed receipts with HSM-certified short-lived keys and shared revocation, event hash
chains with external checkpoints, OAuth 2.1 with DPoP, encrypted backups, and
point-in-time recovery and standby failover drills.

Not done yet:

- An independent security review.
- Failover and restore drills on a production-sized deployment with production
  secrets and automatic failover (Patroni or a managed service).
- VectorLedger evidence throughput: about 10 purchases per second per node. Batching
  needs atomic multi-entry posting in VectorLedger, which does not exist yet.
- YugabyteDB support, which is experimental: the database tests pass on it but are
  about 100 times slower, and the recovery drills are PostgreSQL-only.
- SPIRE workload attestation is a prototype. It passes against a real SPIRE server and
  agent (`scripts/spire_test_env.sh`, CI job `test-spire`).
- Test coverage at the 80% target (currently 75.3%).

---

## Documentation

| Topic | Document |
|---|---|
| Agent identity, delegation and spend, end to end | [docs/guides/agent-identity.md](docs/guides/agent-identity.md) |
| Designing agents in AgentProof (agent builder) | [docs/guides/agent-builder.md](docs/guides/agent-builder.md) |
| Spend operations, workers, evidence pipeline, runbook | [docs/OPERATIONS_SPEND.md](docs/OPERATIONS_SPEND.md) |
| OAuth 2.1 design | [docs/design/oauth-authorization.md](docs/design/oauth-authorization.md) |
| Receipt signing keys and revocation | [docs/design/receipt-signing-keys.md](docs/design/receipt-signing-keys.md) |
| Security claims for reviewers | [docs/SECURITY_REVIEW_PACKAGE.md](docs/SECURITY_REVIEW_PACKAGE.md) |
| Database hardening, backups, restore | [docs/DATABASE_HARDENING.md](docs/DATABASE_HARDENING.md) |
| Benchmarks | [docs/BENCHMARKS.md](docs/BENCHMARKS.md) |
| Testing policy and baselines | [docs/TESTING_POLICY.md](docs/TESTING_POLICY.md) |
| API reference | [API-Docs.md](API-Docs.md) |
| Credential layer reference | [docs/CREDENTIAL_LAYER.md](docs/CREDENTIAL_LAYER.md) |

## License

MIT. See [LICENSE](LICENSE).

*A [VectorGuard Labs](https://vectorguardlabs.com) product.*
**Website:** [agentproof.vectorguardlabs.com](https://agentproof.vectorguardlabs.com) |
**PyPI:** [pypi.org/project/vectorguard-agentproof](https://pypi.org/project/vectorguard-agentproof/)
