šŸ” 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.

šŸ¤– API Integration Pack

If you want browser AI assistants or coding agents to wire existing agents into A2SPA, use the public API Integration Pack. It teaches AI how to create agents through the dashboard Builder Pack and how to add runtime code that still routes through the A2SPA API instead of bypassing it.

Provision Through Builder Pack
Logged-in browser assistants can create, rotate, revoke, and toggle agents using the dashboard Builder Pack.
Wrap Existing Agents
Python, JavaScript, and TypeScript starter templates show how to keep an existing agent runtime while routing signed payloads through POST /A2SPA/api/verify_payload.
API Only
The integration pack explicitly forbids direct Firestore writes or replacing A2SPA verification with local-only checks.
API
Runtime rule: generated code should always use the A2SPA API. The supported runtime endpoints are POST /A2SPA/api/verify_payload for sending and GET /A2SPA/api/inbox_for_agent for polling received messages. Use GET /A2SPA/api/logs_for_agent for audit history and troubleshooting.

🧠 Agent Creation

Use the dashboard to create agents. Choose an agent name, decide whether it can send and/or receive, and keep the generated private key in a secure location. If you use a browser-based AI assistant, open the dashboard's Agent Builder Pack for the same flow in a machine-readable format.

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, then poll the receiver inbox if you want to read delivered messages through the 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!

šŸ“„ Polling a Receiver Inbox

HTTP
curl -H "x-api-key: YOUR_API_KEY_HERE" "https://aimodularity.com/A2SPA/api/inbox_for_agent?agent_id=YOUR_RECEIVER_AGENT_ID&limit=25"

Use the inbox endpoint when an existing agent needs to poll for received messages through the A2SPA API. Use /api/logs_for_agent when you want audit history or troubleshooting detail.

šŸ“‹ 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-...
inputYesData sent to agent{"task": "process"}
outputYesAgent'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

ā±ļø Rate Limits

ā³
When a limit is exceeded, the app returns HTTP 429 plus a Retry-After header. This helps protect the platform against abuse while keeping dashboard and API usage predictable for customers.

🚦 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 account-level API token for calling A2SPA endpoints Authenticates API requests and tracks usage

šŸ“Š 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

Verification logs can include ROI values from an agent's stored ROI profile. If no ROI profile is stored, A2SPA uses a default fallback.

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 still cannot be retrieved, but you can now rotate an agent's keypair from the dashboard to issue a replacement.
Can I reset my API key?
Yes. Rotate it from the dashboard. The previous API key is revoked immediately, so update your scripts and agents right away. Stored API keys are hashed, so after migration you only see the full key at issue time.

šŸ¤– 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?
The current dashboard does not expose ROI editing yet. If no stored ROI profile exists, logs use the default fallback values.

šŸ”— Agent Communication

Can agents respond to each other?
Yes. Agents can communicate bidirectionally as long as the sender has send permission and the target has receive permission. Delivery threading is added to the dashboard automatically.
How do agents chain together?
Each agent gets unique keypairs. Agent A signs the payload → sends it to A2SPA → A2SPA verifies and authorizes it before Agent B acts. Full cryptographic chain of custody.

šŸš€ Future Features (Roadmap)

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