šŸ” A2SPA Developer Documentation

Agent-to-Secure Payload Authorization

A2SPA is the cryptographic firewall for AI agents, ensuring that every autonomous action is signed, verified, authorized, and monitored. Build secure agent-to-agent communication with enforced permissions, replay protection, and comprehensive audit trails.

šŸŽ„ Tutorial Video

šŸš€ A2SPA Complete Walkthrough
Watch this comprehensive tutorial to learn how to set up agents, sign payloads, and monitor your A2SPA implementation step by step.
šŸŽÆ
What You'll Learn:
  • Setting up your first A2SPA agent
  • Implementing cryptographic signing
  • Using the dashboard and monitoring tools
  • Best practices for secure agent communication

šŸ“Œ Overview

A2SPA (Agent-to-Secure Payload Authorization) is a secure protocol that enables verified, cryptographically signed payloads between AI agents. This platform allows developers and non-technical users to create, manage, and monitor modular AI agents, all protected by A2SPA.

āœ…
Cryptographic Signatures
Every payload must be signed with the agent's private key
šŸ”’
Agent Permission & Toggle Checks
Granular control over agent send/receive permissions
šŸ”„
Nonce Replay Protection
Prevents replay attacks with unique nonce verification
šŸ“Š
ROI Logging Per Agent
Track time saved and value generated by each agent
šŸ’°
Pay-as-you-go Billing
$0.01 per verification with transparent usage tracking
šŸ“‹
Tamper-proof Audit Trail
Complete logging of all agent interactions and verifications

šŸš€ Getting Started

Sign Up

Login

Forgot Password

šŸ’”
Pro Tip: Make sure to keep your agent private keys secure. They cannot be retrieved once lost.

🧠 Agent Creation

Use the dashboard or POST /api/create_agent to create agents with configurable permissions:

JSON
{
  "agent_name": "calendarAgent",
  "permissions": {
    "send": true,
    "receive": false
  },
  "enabled": true
}
āœ…
This returns:
  • public_key and private_key (PEM format)
  • agent_id (e.g., abc123_calendarAgent)
šŸ”
Important: Keep the private key secure. It cannot be retrieved again.

Agent Permissions Explained

Permission Description
send Can initiate actions or payloads
receive Can be a target agent and receive payloads

šŸ” Helps prevent abuse even if an agent is compromised.

šŸ–Šļø Sending Messages

To send a message (payload), you need to create it, hash it, sign it, and send it to A2SPA for verification. Here's how it works:

šŸ’” 4 Simple Steps

  1. Create a message with sender and receiver IDs, timestamp, and a unique code (nonce).
  2. Hash the message to create a unique fingerprint.
  3. Sign the message with your private key to prove it's from you.
  4. Send the message and signature to A2SPA's API.

šŸ”§ Complete Example

What You Need:

šŸ Python Code to Send a Message

import json, uuid, requests, hashlib
from datetime import datetime, timezone
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding

# ============ Settings ============
API_BASE = "https://aimodularity.com/A2SPA"
API_KEY = "YOUR_API_KEY_HERE"  # Get from dashboard
USER_ID = "your_user_id"
SENDER_AGENT_ID = f"{USER_ID}_my_agent_send"
RECEIVER_AGENT_ID = f"{USER_ID}_my_agent_receive"
PRIVATE_KEY_PATH = "your_sender_agent.priv.pem"

# ============ Helper Function ============
def sha256_hex(obj):
    """Create a hash of the message, excluding 'hash' and 'signature' fields"""
    clean = {k: v for k, v in obj.items() if k not in ["hash", "signature"]}
    data = json.dumps(clean, sort_keys=True).encode()
    return hashlib.sha256(data).hexdigest()

# ============ Step 1: Create Message ============
payload = {
    "agent_id": SENDER_AGENT_ID,
    "target_agent_id": RECEIVER_AGENT_ID,
    "timestamp": datetime.now(timezone.utc).isoformat(),
    "nonce": str(uuid.uuid4()),  # Unique code to prevent reuse
    "input": {"message": "Hello from sender agent!"},
    "output": {"status": "ready"}
}
print("āœ… Step 1: Message created")

# ============ Step 2: Hash the Message ============
payload["hash"] = sha256_hex(payload)
print(f"āœ… Step 2: Hash created: {payload['hash'][:16]}...")

# ============ Step 3: Sign the Message ============
with open(PRIVATE_KEY_PATH, "rb") as f:
    PRIVATE_KEY_PEM = f.read()

private_key = serialization.load_pem_private_key(
    PRIVATE_KEY_PEM, 
    password=None
)

clean_for_sign = {k: v for k, v in payload.items() 
                  if k not in ["hash", "signature"]}
message = json.dumps(clean_for_sign, sort_keys=True).encode()

signature_hex = private_key.sign(
    message, 
    padding.PKCS1v15(), 
    hashes.SHA256()
).hex()
print(f"āœ… Step 3: Signature created: {signature_hex[:16]}...")

# ============ Step 4: Send to A2SPA ============
resp = requests.post(
    f"{API_BASE}/api/verify_payload",
    headers={
        "Content-Type": "application/json",
        "x-api-key": API_KEY
    },
    json={
        "payload": payload,
        "signature": signature_hex
    }
)

print(f"\nšŸŽÆ Result:")
print(f"Status Code: {resp.status_code}")
print(f"Response: {resp.text}")

if resp.status_code == 200:
    print("\nāœ… Success! Message verified and logged.")
else:
    print("\nāŒ Error: Check the response message.")
šŸŽÆ Tip: Copy this code, replace YOUR_API_KEY_HERE, your_user_id, and the private key file path with your values from the dashboard, and run it. It should work right away!

šŸ“‹ Message Fields

FieldRequired?DescriptionExample
agent_idYesSender's agent IDabc123_myAgent
target_agent_idYesReceiver's agent IDdef456_otherAgent
timestampYesUTC time of message2025-10-07T14:30:00Z
nonceYesUnique code to prevent reusea1b2c3d4-e5f6-...
inputNoData sent to agent{"task": "process"}
outputNoAgent's response{"result": "done"}
hashYesMessage fingerprinta3f8e2b9c1d...

āš ļø Common Errors

ErrorCauseFix
Signature verification failedWrong hash or private keyHash first, then sign with correct key.
Agent not foundWrong agent IDCopy ID exactly from dashboard.
Timestamp too oldMessage older than 2 minutesSend immediately using datetime.now(timezone.utc).
Replay attack detectedReused nonceUse a new str(uuid.uuid4()).

šŸ›”ļø Security Features

šŸ” Replay Protection

🚦 Agent Toggle & Permissions

šŸ”
Replay Attacks: What Are They?
A replay attack is when someone reuses a valid payload to trigger it again. A2SPA blocks this silently and logs the attempt.

🚨 Common Mistakes to Avoid

Mistake Fix
Reusing a nonce or timestamp Use uuid4() and datetime.utcnow()
Sending wrong agent_id Match dashboard agent exactly
Forgetting to hash the payload Call compute_payload_hash()
Signing before adding the hash Always hash first, then sign
Payload too old (>2 min) Send immediately, use NTP-synced clocks
Agent is toggled OFF Go to dashboard and toggle it ON

šŸ” Key Terms for Beginners

Term What It Means Why It Matters
Nonce One-time string (UUID) Stops replay attacks
Hash Fingerprint of the payload Proves nothing changed
Signature Encrypted proof of identity Proves you sent it
API Key Your agent's access ID Tracks usage and billing

šŸ“Š Dashboard Features

The A2SPA dashboard provides comprehensive monitoring and management capabilities for your agents:

šŸ“ˆ Key Components

šŸ“‹ Log Details

Each log entry contains:

āš ļø Credit Status Indicators

Status Balance Indicator API Access
Normal >10 tokens Green status Full access
Warning <10 tokens āš ļø Yellow banner Full access
Critical 0 tokens šŸ”“ Red banner API disabled

šŸ’° Billing & ROI

šŸ’³ Pricing Model

A2SPA uses a simple, transparent pay-as-you-go model:

šŸ“ˆ ROI Tracking

Each agent can define its ROI profile to track value generation:

JSON - Custom ROI
{
  "roi": {
    "time_saved_minutes": 3,
    "value_usd": 0.08
  }
}

Default ROI fallback if not provided:

JSON - Default ROI
{ 
  "time_saved_minutes": 2, 
  "value_usd": 0.05 
}
šŸ“Š
ROI Visibility: Track ROI across dashboard, CSV exports, and individual log entries. Example display: "šŸ“ˆ ROI: 2 min saved ($0.05)"

ā“ Frequently Asked Questions

šŸ”‘ Account & Security

What happens if my balance hits 0?
Agent calls are blocked, a red alert is shown in the dashboard, but logs remain visible for review.
What if I lose my private key?
Private keys cannot be retrieved. You must create a new agent with fresh keypairs.
Can I reset my API key?
This feature is currently not available but will be added in a future release.

šŸ¤– Agent Management

Can I run multiple agents?
Yes! Each agent has its own keypair, logs, toggle status, and independent tracking.
How do I disable an agent instantly?
Use the toggle switch in your dashboard to turn agents ON/OFF immediately.
Can I customize ROI values?
Yes, you can manually report ROI values per payload or leave blank to use defaults.

šŸ”— Agent Communication

Can agents respond to each other?
Yes! Use the reply_to field in payloads. Both agents must be A2SPA-enabled for verification.
How do agents chain together?
Each agent gets unique keypairs. Agent A signs payload → sends to A2SPA → Agent B verifies before execution. Full cryptographic chain of custody.

šŸš€ Future Features (Roadmap)

šŸ’”
Need Help?
Email: hello@aiblockchainventures.com
Website: https://aimodularity.com