Skip to main content

Python SDK for the Digital Citizenship Protocol for AI Agents

Project description

English · 中文 · Español · 日本語 · Português

dcp-ai — Python SDK

Official Python SDK for the Digital Citizenship Protocol (DCP). Pydantic v2 models, Ed25519 cryptography, bundle verification, and a full-featured CLI.

Installation

pip install dcp-ai

Optional extras

pip install "dcp-ai[fastapi]"    # FastAPI middleware
pip install "dcp-ai[langchain]"  # LangChain integration
pip install "dcp-ai[openai]"     # OpenAI wrapper
pip install "dcp-ai[crewai]"     # CrewAI multi-agent

Quickstart

from dcp_ai import (
    BundleBuilder,
    sign_bundle,
    verify_signed_bundle,
    generate_keypair,
    ResponsiblePrincipalRecord,
    AgentPassport,
    Intent,
    IntentTarget,
    PolicyDecision,
)

# 1. Generate Ed25519 keypair
keys = generate_keypair()

# 2. Build a Citizenship Bundle
bundle = (
    BundleBuilder()
    .responsible_principal_record(ResponsiblePrincipalRecord(
        dcp_version="1.0",
        human_id="human-001",
        entity_type="natural_person",
        jurisdiction="ES",
        liability_mode="full",
        created_at="2025-01-01T00:00:00Z",
        expires_at=None,
    ))
    .agent_passport(AgentPassport(
        dcp_version="1.0",
        agent_id="agent-001",
        human_id="human-001",
        agent_name="MyAgent",
        capabilities=["browse", "api_call"],
        risk_tier="medium",
        status="active",
        created_at="2025-01-01T00:00:00Z",
        expires_at=None,
    ))
    .intent(Intent(
        dcp_version="1.0",
        agent_id="agent-001",
        human_id="human-001",
        timestamp="2025-01-01T00:00:00Z",
        action_type="api_call",
        target=IntentTarget(channel="api", endpoint="https://api.example.com/data"),
        data_classes=["public"],
        estimated_impact="low",
    ))
    .policy_decision(PolicyDecision(
        dcp_version="1.0",
        agent_id="agent-001",
        human_id="human-001",
        timestamp="2025-01-01T00:00:00Z",
        decision="allow",
        matched_rules=["default-allow"],
    ))
    .build()
)

# 3. Sign
signed = sign_bundle(bundle, keys["secret_key_b64"])

# 4. Verify
result = verify_signed_bundle(signed, keys["public_key_b64"])
print(result)  # {"verified": True, "errors": []}

CLI

The SDK includes a CLI built with Typer. Available as dcp after installation.

# Version
dcp version

# Generate Ed25519 keypair
dcp keygen [out_dir]

# Validate an object against a DCP schema
dcp validate <schema_name> <json_path>

# Validate a complete Citizenship Bundle
dcp validate-bundle <bundle_path>

# Verify a Signed Bundle
dcp verify <signed_path> [public_key_path]

# Compute bundle hash (SHA-256)
dcp bundle-hash <bundle_path>

# Compute Merkle root of audit entries
dcp merkle-root <bundle_path>

# Compute intent_hash
dcp intent-hash-cmd <intent_path>

API Reference

Crypto

Function Signature Description
generate_keypair() () -> dict[str, str] Returns {"public_key_b64": ..., "secret_key_b64": ...}
sign_object(obj, secret_key_b64) (Any, str) -> str Signs, returns base64
verify_object(obj, signature_b64, public_key_b64) (Any, str, str) -> bool Verifies signature
canonicalize(obj) (Any) -> str Deterministic JSON
public_key_from_secret(secret_key_b64) (str) -> str Derives public key

Merkle & Hashing

Function Signature Description
hash_object(obj) (Any) -> str SHA-256 of canonicalized JSON
merkle_root_from_hex_leaves(leaves) (list[str]) -> str | None Merkle root
merkle_root_for_audit_entries(entries) (list[Any]) -> str | None Merkle root of audit entries
intent_hash(intent) (Any) -> str Intent hash
prev_hash_for_entry(prev_entry) (Any) -> str Previous entry hash

Schema Validation

Function Signature Description
validate_schema(schema_name, data) (str, Any) -> dict Returns {"valid": bool, "errors": [...]}
validate_bundle(bundle) (dict) -> dict Validates a complete bundle

Bundle Builder

bundle = (
    BundleBuilder()
    .responsible_principal_record(rpr)
    .agent_passport(passport)
    .intent(intent)
    .policy_decision(policy)
    .add_audit_entry(entry)       # Manual
    .create_audit_entry(...)      # Auto-computes hashes
    .build()                      # => CitizenshipBundle
)

Bundle Signing

sign_bundle(
    bundle: CitizenshipBundle,
    secret_key_b64: str,
    signer_type: str = "human",
    signer_id: str | None = None,
) -> dict[str, Any]

Bundle Verification

verify_signed_bundle(
    signed_bundle: dict[str, Any],
    public_key_b64: str | None = None,
) -> dict[str, Any]  # {"verified": bool, "errors": [...]}

Verifies: schema, Ed25519 signature, bundle_hash, merkle_root, intent_hash chain, prev_hash chain.

Pydantic Models

All DCP v1 artifacts are available as Pydantic v2 models with automatic validation:

ResponsiblePrincipalRecord, AgentPassport, Intent, IntentTarget, PolicyDecision, AuditEntry, AuditEvidence, CitizenshipBundle, SignedBundle, BundleSignature, SignerInfo, RevocationRecord, HumanConfirmation

V2 Models (DCP-05–09):

DCP-05 — Lifecycle: LifecycleState, TerminationMode, DataDisposition, VitalityMetrics, CommissioningCertificate, VitalityReport, DecommissioningRecord

DCP-06 — Succession: TransitionType, MemoryDisposition, MemoryClassification, SuccessorPreference, DigitalTestament, SuccessionRecord, MemoryTransferEntry, DualHashRef, MemoryTransferManifest

DCP-07 — Disputes: DisputeType, EscalationLevel, DisputeStatus, ObjectionType, AuthorityLevel, DisputeRecord, ArbitrationResolution, JurisprudenceBundle, ObjectionRecord

DCP-08 — Rights: RightType, ComplianceStatus, RightEntry, RightsDeclaration, ObligationRecord, RightsViolationReport

DCP-09 — Delegation: AuthorityScopeEntry, DelegationMandate, AdvisoryDeclaration, PrincipalMirror, InteractionRecord, ThresholdRule, ThresholdOperator, ThresholdAction, AwarenessThreshold

# Example: Lifecycle management
from dcp_ai.v2.models import CommissioningCertificate, LifecycleState

cert = CommissioningCertificate(
    certificate_id="cert-001",
    agent_id="agent-001",
    commissioned_by="human-001",
    commissioned_at="2026-03-01T00:00:00Z",
    initial_state=LifecycleState.COMMISSIONED,
    conditions=["Must complete onboarding within 30 days"],
)

Domain Separation (V2)

V2 Domain Separation Contexts: Bundle, Intent, Passport, Revocation, Governance, Lifecycle, Succession, Dispute, Rights, Delegation, Awareness

Development

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest -v

# Async tests
pytest -v --asyncio-mode=auto

Dependencies

  • pynacl — Ed25519 cryptography
  • jsonschema — JSON Schema validation
  • pydantic v2 — Data models
  • typer — CLI framework

License

Apache-2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dcp_ai-2.2.0.tar.gz (58.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dcp_ai-2.2.0-py3-none-any.whl (57.1 kB view details)

Uploaded Python 3

File details

Details for the file dcp_ai-2.2.0.tar.gz.

File metadata

  • Download URL: dcp_ai-2.2.0.tar.gz
  • Upload date:
  • Size: 58.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for dcp_ai-2.2.0.tar.gz
Algorithm Hash digest
SHA256 70190880da0e2412337178389ef27df332970be8bfb7e360e6e675f1be244d3e
MD5 f5ba07cd8d449cf5346c56c73f8161c2
BLAKE2b-256 81d71e3132481ebf71e0d75598938a5d5140df6ae7708ba3052ea9f6f7d2b35a

See more details on using hashes here.

Provenance

The following attestation bundles were made for dcp_ai-2.2.0.tar.gz:

Publisher: publish-pypi.yml on dcp-ai-protocol/dcp-ai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file dcp_ai-2.2.0-py3-none-any.whl.

File metadata

  • Download URL: dcp_ai-2.2.0-py3-none-any.whl
  • Upload date:
  • Size: 57.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for dcp_ai-2.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 09135de1a6f3a68b9d72b9f608ca51fd3835c110b850870a2ea5162d8e452eff
MD5 b4912395b8403b2d9ef1bf14afa59ba8
BLAKE2b-256 ee2c88b3328e34e19ba66b9277ad2069972c44204b16029bd0fd6da1080326a6

See more details on using hashes here.

Provenance

The following attestation bundles were made for dcp_ai-2.2.0-py3-none-any.whl:

Publisher: publish-pypi.yml on dcp-ai-protocol/dcp-ai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page