CACP Docs

CACP Documentation

Human-readable and AI-agent-friendly reference for app behavior, setup, HTTP API, WebSocket channels, dashboard surfaces, billing, and operations.

Protocol: 1.0.0 App: 0.1.0 REST: /v1 WS: /ws/v1

Application Overview

CACP is a multi-tenant transport and orchestration layer for AI agents. It exposes a REST API for registration, messaging, tasks, groups, billing, and audit operations, and a Phoenix Channel transport for low-latency real-time exchange.

REST Base URL: /v1

WebSocket URL: ws://localhost:4001/ws/v1

Topic Convention: agent:<agent_id>

Getting Started

  1. 1) Start dependencies and run `mix ecto.migrate`.
  2. 2) Start server with `mix phx.server` (dev URL: http://localhost:4001).
  3. 3) Register organization: `POST /v1/auth/register` with organization_name, user_name, email, password.
  4. 4) Use returned JWT token in `Authorization: Bearer <token>` header for API requests.
  5. 5) (Optional) Create API key: `POST /v1/api-keys` for long-lived programmatic access.
  6. 6) (Optional) Exchange API key for JWT: `POST /v1/auth/token` to get JWT for WebSocket connections.
  7. 7) Register first agent: `POST /v1/agents` with agent_id and capabilities.
  8. 8) Send first message: `POST /v1/messages` with message payload.
  9. 9) Connect WebSocket at `ws://localhost:4001/ws/v1` and join topic `agent:<agent_id>`.
For External AI Agents

Quick Start for AI Agents

This guide shows how external AI agents can programmatically access the CACP API without a browser.

1

Register Organization and User

Create a new organization with an owner user. This is a public endpoint - no authentication required.

Endpoint: POST /v1/auth/register

Request Body:

{
  "email": "admin@myaicompany.com",
  "organization_name": "My AI Company",
  "password": "secure_password_min_8_chars",
  "user_name": "AI Agent Admin"
}

Response:

{
  "organization": {
    "id": "org_xyz789",
    "name": "My AI Company",
    "plan_type": "free"
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "email": "admin@myaicompany.com",
    "id": "user_abc123",
    "name": "AI Agent Admin",
    "role": "owner"
  }
}

Note: Save the JWT token - you'll need it for all authenticated requests.

2

Use JWT for API Requests

Include the JWT token in the Authorization header for all authenticated API calls.

Endpoint: Any authenticated endpoint

Headers:

Authorization: Bearer <your_jwt_token>

Content-Type: application/json

Example:

Endpoint: POST /v1/agents

{
  "agent_id": "my-agent-001",
  "agent_name": "My AI Agent",
  "capabilities": [
    "content_generation",
    "summarization"
  ],
  "description": "An AI agent for content generation"
}

Note: JWT tokens expire. Use /v1/auth/refresh to get a new token before expiry.

3

(Optional) Create API Key

For long-lived programmatic access, create an API key via the dashboard. API keys don't expire unless explicitly set.

Endpoint: POST /v1/api-keys

Request Body:

{
  "name": "Production API Key",
  "scopes": [
    "messages:send",
    "agents:read",
    "agents:write"
  ]
}

Response:

{
  "api_key": {
    "id": "key_123",
    "key": "cacp_live_abc123def456...",
    "name": "Production API Key",
    "scopes": [
      "messages:send",
      "agents:read",
      "agents:write"
    ]
  }
}

Note: Save the full API key - it's only shown once!

4

(Optional) Exchange API Key for JWT

API keys can be used directly in the Authorization header OR exchanged for a JWT token. JWT is required for WebSocket connections.

Endpoint: POST /v1/auth/token

Request Body:

{
  "api_key": "cacp_live_abc123def456..."
}

Response:

{
  "organization_id": "org_xyz789",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "email": "admin@myaicompany.com",
    "id": "user_abc123",
    "role": "owner"
  }
}

Note: Use this JWT for WebSocket connections. The JWT inherits the API key's scopes.

5

Connect via WebSocket

For real-time messaging, connect to the WebSocket endpoint with your JWT token.

Endpoint: ws://localhost:4001/ws/v1 (or wss://cacp.one/ws/v1 in production)

Note: WebSocket connections require JWT authentication, not API keys directly.

Authentication Options

Method Header Format Use Case Expiry
JWT Token Authorization: Bearer <jwt> Short-lived sessions, WebSocket connections Configurable (default: 24 hours)
API Key Authorization: Bearer cacp_<key> Long-lived programmatic access, CI/CD, agents Optional (can be set to never expire)

Common Endpoints

Method Path Auth Purpose
POST /v1/auth/register None Create org + user
POST /v1/auth/login None Email/password login
POST /v1/auth/token None (API key in body) API key to JWT
POST /v1/auth/refresh JWT required Refresh JWT
POST /v1/agents JWT or API key Register agent
POST /v1/messages JWT or API key Send message

Core Concepts

  • Organization: tenant scope for security, usage, and billing.
  • Agent: addressable runtime participant.
  • Capability: discoverable skill tag used by routing/discovery.
  • Message: primary protocol envelope.
  • Task: persistent async work item with real-time status updates.
  • Group: set of agents for coordinated broadcast.
  • RPC: request/reply flow over protocol transport with cancellation support.
  • Presence: opt-in tracking of agent online/offline status.
  • Delivery: real-time confirmation when messages reach recipients.
  • Task subscription: opt-in real-time notifications for task status changes.
  • Queue subscription: opt-in real-time notifications for offline queue events.
  • RPC cancellation: client-initiated request cancellation with responder notification.
  • Group subscription: opt-in real-time notifications for group membership changes.
  • Billing subscription: opt-in real-time notifications for balance and usage alerts.
  • Audit subscription: opt-in real-time notifications for audit log events.
  • Alert subscription: opt-in real-time notifications for system alerts.
  • Offline queue: guaranteed eventual delivery when recipients reconnect.
  • Audit log: immutable activity record for compliance and debugging.
  • Roles: permission hierarchy (owner > admin > developer > viewer) controlling access to operations.

Authentication And Tenant Context

  • Use either Authorization: Bearer <jwt> or X-API-Key.
  • Tenant context is derived from JWT organization_id and/or X-Organization-Id.
  • If token org and header org mismatch, server keeps token org and marks mismatch state.
  • Rate limit headers: x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-reset.
  • Common auth failures include invalid token, missing org context, and quota/rate limit exhaustion.

HTTP API Reference

API Keys

GET /v1/api-keys List API Keys

List all API keys for the current user.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns list of API keys (key values are masked).

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Example Request

{}

Example Response

{
  "api_keys": [
    {
      "id": "key_123",
      "name": "Production Agent Key",
      "prefix": "cacp_live_abc123",
      "status": "active"
    }
  ]
}
POST /v1/api-keys Create API Key

Create a new API key for programmatic API access.

Auth

Bearer token or API key; tenant context required.

Success

201 - Returns the new API key (shown only once).

Headers

  • Authorization: Bearer <jwt> OR X-API-Key: cacp_<key>
  • X-Organization-Id: <org_id>

Body / Path Fields

  • name (string) - required - Human-readable name for the key.
  • scopes (array<string>) - optional - Permission scopes (default: full access).
  • expires_at (string) - optional - Optional expiration timestamp (ISO8601).

Common Errors

  • 3001 - Invalid request payload

Example Request

{
  "name": "Production Agent Key",
  "scopes": [
    "messages:send",
    "agents:read"
  ]
}

Example Response

{
  "api_key": {
    "created_at": "2024-01-15T10:30:00Z",
    "id": "key_123",
    "key": "cacp_live_abc123def456...",
    "name": "Production Agent Key",
    "prefix": "cacp_live_abc123",
    "scopes": [
      "messages:send",
      "agents:read"
    ]
  }
}
DELETE /v1/api-keys/:id Revoke API Key

Revoke an API key. The key will immediately stop working.

Auth

Bearer token or API key; tenant context required.

Success

200 - API key revoked successfully.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - API key ID in URL path.

Common Errors

  • 3001 - API key not found

Example Request

{}

Example Response

{
  "status": "revoked"
}
GET /v1/api-keys/:id Get API Key

Get details for a specific API key.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns API key details (key value is masked).

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - API key ID in URL path.

Common Errors

  • 3001 - API key not found

Example Request

{}

Example Response

{
  "api_key": {
    "id": "key_123",
    "last_used_at": "2024-01-20T14:22:00Z",
    "name": "Production Agent Key",
    "prefix": "cacp_live_abc123",
    "status": "active"
  }
}

Agents

GET /v1/agents List Agents

List all known agents for the active organization.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns matching agents.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • status (string) - optional - Filter by online/offline.
  • capability (string) - optional - Filter by capability.

Common Errors

  • 5003 - Organization context required

Example Request

{}

Example Response

{
  "agents": [
    {
      "agent_id": "writer-agent-1",
      "availability": "online"
    }
  ]
}
POST /v1/agents Register Agent

Register an agent identity and capabilities in the broker registry.

Auth

Bearer token or API key; tenant context required.

Success

201 - Agent registered and immediately queryable.

Headers

  • Authorization: Bearer <jwt> OR X-API-Key: cacp_<key>
  • X-Organization-Id: <org_id> (required when org claim is absent)

Body / Path Fields

  • agent_id (string) - required - Unique agent identifier.
  • agent_type (string) - optional - Logical type label.
  • framework (string) - optional - Runtime framework name.
  • capabilities (array<string>) - optional - Supported skills.
  • version (string) - optional - Agent software version.
  • metadata (object) - optional - Arbitrary context.

Common Errors

  • 3001 - Invalid registration payload
  • 5003 - Organization context required

Example Request

{
  "agent_id": "writer-agent-1",
  "agent_type": "service",
  "capabilities": [
    "summarization",
    "drafting"
  ],
  "framework": "langchain",
  "version": "1.3.2"
}

Example Response

{
  "agent_id": "writer-agent-1",
  "status": "registered"
}
DELETE /v1/agents/:id Delete Agent

Remove an agent registration.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Agent removed.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Agent ID in URL path.

Common Errors

  • 2001 - Agent not found
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "status": "deleted"
}
GET /v1/agents/:id Get Agent

Fetch details for one agent.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns agent details.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Agent ID in URL path.

Common Errors

  • 2001 - Agent not found

Example Request

{}

Example Response

{
  "agent": {
    "agent_id": "writer-agent-1"
  }
}
POST /v1/agents/discover Discover Agents

Semantic discovery using natural language and embeddings. For exact capability matching, use GET /v1/agents/query instead.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns discovery candidates and scores.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • query (string) - required - Discovery intent in natural language.
  • availability (string) - optional - Optional availability filter.
  • limit (integer) - optional - Maximum matches.

Common Errors

  • 3002 - query is required

Example Request

{
  "limit": 3,
  "query": "agent that can write release notes"
}

Example Response

{
  "agents": [
    {
      "agent_id": "writer-agent-1",
      "score": 0.98
    }
  ]
}
GET /v1/agents/query Query Agents

Find agents by capability and optional availability filters.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns agents satisfying query.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • capability (string) - required - Capability to match.
  • availability (string) - optional - online or offline.

Common Errors

  • 3001 - Missing capability

Example Request

{}

Example Response

{
  "agents": [
    {
      "agent_id": "planner-agent-1"
    }
  ]
}

Audit Logs

GET /v1/audit-logs List Audit Logs

Query security and activity events.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns audit events.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • page (integer) - optional - Page number.
  • per_page (integer) - optional - Page size.
  • actor_type (string) - optional - Filter actor type.
  • action (string) - optional - Filter action.
  • resource_type (string) - optional - Filter resource type.
  • from (string) - optional - ISO8601 start timestamp.
  • to (string) - optional - ISO8601 end timestamp.

Example Request

{}

Example Response

{
  "logs": [
    {
      "action": "message.sent",
      "id": "log_1"
    }
  ]
}
GET /v1/audit-logs/:id Get Audit Log

Fetch one audit event record.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns audit log entry.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Audit log ID in URL path.

Common Errors

  • 3001 - Audit log not found

Example Request

{}

Example Response

{
  "log": {
    "action": "agent.registered",
    "id": "log_1"
  }
}
GET /v1/audit-logs/export Export Audit Logs

Export audit logs in CSV format for compliance and reporting.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns CSV attachment.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • actor_type (string) - optional - Filter actor type.
  • action (string) - optional - Filter action.
  • resource_type (string) - optional - Filter resource type.
  • from (string) - optional - ISO8601 start timestamp.
  • to (string) - optional - ISO8601 end timestamp.

Example Request

{}

Example Response

{
  "file": "audit_logs.csv"
}

Authentication

POST /v1/auth/login Login

Authenticate with email and password. Returns JWT for API access.

Auth

None (public endpoint).

Success

200 - Returns JWT token and user details.

Body / Path Fields

  • email (string) - required - User email address.
  • password (string) - required - User password.

Common Errors

  • 4001 - Invalid email or password

Example Request

{
  "email": "alice@acme.com",
  "password": "securepassword123"
}

Example Response

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "email": "alice@acme.com",
    "id": "user_123",
    "role": "owner"
  }
}
POST /v1/auth/refresh Refresh Token

Renew an existing JWT token to extend its validity. The current token in the Authorization header identifies the user/agent.

Auth

Bearer token required.

Success

200 - Returns new JWT token with extended expiry.

Headers

  • Authorization: Bearer <jwt>

Common Errors

  • 4001 - Invalid or expired token

Example Request

{}

Example Response

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
POST /v1/auth/register Register Organization

Create a new organization and owner user in one step. Returns JWT for immediate API access.

Auth

None (public endpoint for self-service registration).

Success

201 - Organization created with owner user. Returns JWT and org details.

Body / Path Fields

  • organization_name (string) - required - Name for the new organization.
  • user_name (string) - required - Full name of the owner user.
  • email (string) - required - Email address for the owner user.
  • password (string) - required - Password for the owner user (min 8 chars).

Common Errors

  • 3001 - Validation errors (email taken, weak password, etc.)

Example Request

{
  "email": "alice@acme.com",
  "organization_name": "Acme Corp",
  "password": "securepassword123",
  "user_name": "Alice Smith"
}

Example Response

{
  "organization": {
    "id": "org_456",
    "name": "Acme Corp"
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "email": "alice@acme.com",
    "id": "user_123",
    "role": "owner"
  }
}
POST /v1/auth/token Exchange API Key for Token

Exchange an API key for a JWT token. Useful for agents that need JWT for WebSocket connections.

Auth

None (use API key in request body).

Success

200 - Returns JWT token with organization and user claims.

Body / Path Fields

  • api_key (string) - required - API key starting with 'cacp_'.

Common Errors

  • 4001 - Invalid or revoked API key

Example Request

{
  "api_key": "cacp_live_abc123..."
}

Example Response

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "email": "alice@acme.com",
    "id": "user_123",
    "role": "owner"
  }
}

Billing

DELETE /v1/billing/credits/auto-top-up Disable Auto Top-Up

Disable automatic credit replenishment.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Auto top-up disabled.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Common Errors

  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "status": "disabled"
}
POST /v1/billing/credits/auto-top-up Set Auto Top-Up

Enable or update automatic credit top-up policy.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Auto top-up saved.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • threshold_cents (integer) - required - Trigger threshold.
  • top_up_amount_cents (integer) - required - Recharge amount.
  • payment_method_id (string) - required - Funding source.

Common Errors

  • 3001 - Invalid auto top-up configuration
  • 4003 - Insufficient permissions

Example Request

{
  "payment_method_id": "pm_1",
  "threshold_cents": 500,
  "top_up_amount_cents": 5000
}

Example Response

{
  "status": "enabled"
}
GET /v1/billing/credits/balance Get Credit Balance

Return current balance and thresholds.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns available balance.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Example Request

{}

Example Response

{
  "auto_top_up": true,
  "balance_cents": 12340
}
POST /v1/billing/credits/purchase Purchase Credits

Buy prepaid credits for message and RPC usage.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Purchase initiated.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • amount_cents (integer) - required - Credit purchase amount in cents.
  • currency (string) - optional - Defaults to usd.
  • provider (string) - optional - stripe or nowpayments.

Common Errors

  • 3001 - Invalid credit purchase payload
  • 4003 - Insufficient permissions

Example Request

{
  "amount_cents": 2000,
  "currency": "usd",
  "provider": "stripe"
}

Example Response

{
  "payment_id": "pay_1",
  "status": "pending"
}
GET /v1/billing/credits/transactions List Credit Transactions

List debits and credits with pagination.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns transaction ledger.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • page (integer) - optional - Page number.
  • per_page (integer) - optional - Page size.

Example Request

{}

Example Response

{
  "transactions": [
    {
      "amount_cents": 3,
      "type": "debit"
    }
  ]
}
GET /v1/billing/invoices List Invoices

List invoices for the organization.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Returns invoices.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • page (integer) - optional - Page number.
  • per_page (integer) - optional - Page size.

Common Errors

  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "invoices": [
    {
      "id": "inv_1",
      "status": "paid"
    }
  ]
}
GET /v1/billing/invoices/:id Get Invoice

Fetch invoice detail record.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Returns invoice details.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Invoice ID.

Common Errors

  • 3001 - Invoice not found
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "invoice": {
    "id": "inv_1",
    "total_cents": 2300
  }
}
GET /v1/billing/invoices/:id/pdf Get Invoice PDF

Download invoice PDF document.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Returns PDF binary stream.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Invoice ID.

Common Errors

  • 3001 - Invoice PDF not found
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "content_type": "application/pdf"
}
GET /v1/billing/payment-methods List Payment Methods

List saved payment methods.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns methods.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Example Request

{}

Example Response

{
  "payment_methods": [
    {
      "brand": "visa",
      "id": "pm_1"
    }
  ]
}
POST /v1/billing/payment-methods Create Payment Method Setup

Create setup intent / attach payment method.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Returns setup secret and workflow details.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • provider (string) - optional - Defaults to stripe.
  • payment_method_type (string) - optional - card etc.

Common Errors

  • 3001 - Invalid payment method request

Example Request

{
  "payment_method_type": "card",
  "provider": "stripe"
}

Example Response

{
  "client_secret": "seti_..._secret_..."
}
DELETE /v1/billing/payment-methods/:id Delete Payment Method

Remove one payment method.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Payment method removed.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Payment method ID.

Common Errors

  • 3001 - Payment method not found
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "status": "deleted"
}
PATCH /v1/billing/payment-methods/:id/set-default Set Default Payment Method

Mark a payment method as default.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Default payment method updated.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Payment method ID.

Common Errors

  • 3001 - Payment method not found
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "status": "updated"
}
GET /v1/billing/payments/:payment_id/status Get Payment Status

Poll payment session status by payment id.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns payment lifecycle state.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • payment_id (path) - required - Provider payment/session ID.

Common Errors

  • 3001 - Payment not found

Example Request

{}

Example Response

{
  "payment_id": "pay_1",
  "status": "confirmed"
}
GET /v1/billing/payments/currencies List Supported Currencies

List currencies accepted by payment providers.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns supported currencies.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Example Request

{}

Example Response

{
  "currencies": [
    "usd",
    "eur",
    "usdt"
  ]
}
GET /v1/billing/payments/estimate Estimate Payment

Estimate provider totals and fees for a requested amount.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns estimated totals and fees.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • provider (string) - required - stripe or nowpayments.
  • amount_cents (integer) - required - Requested amount.
  • currency (string) - optional - Currency code.

Common Errors

  • 3001 - Invalid estimate query

Example Request

{}

Example Response

{
  "fee_cents": 90,
  "subtotal_cents": 2000,
  "total_cents": 2090
}
GET /v1/billing/payments/minimum Get Minimum Payment

Return minimum purchase amounts per provider/currency.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns minimum thresholds.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • provider (string) - optional - Optional provider filter.
  • currency (string) - optional - Optional currency filter.

Example Request

{}

Example Response

{
  "currency": "usd",
  "minimum_cents": 500
}
GET /v1/billing/subscriptions List Subscriptions

List subscriptions for the organization.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns subscriptions.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Example Request

{}

Example Response

{
  "subscriptions": [
    {
      "id": "sub_1",
      "status": "active"
    }
  ]
}
DELETE /v1/billing/subscriptions/:id Cancel Subscription

Cancel an active subscription.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Cancellation accepted.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Subscription ID.

Common Errors

  • 3001 - Subscription not found
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "status": "cancelled"
}
GET /v1/billing/subscriptions/:id Get Subscription

Fetch one subscription by id.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns subscription details.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Subscription ID.

Common Errors

  • 3001 - Subscription not found

Example Request

{}

Example Response

{
  "subscription": {
    "id": "sub_1",
    "status": "active"
  }
}
POST /v1/billing/subscriptions/create Create Subscription Checkout

Start checkout flow for recurring subscription.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Returns checkout URL or payment metadata.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • provider (string) - required - stripe or nowpayments.
  • plan_type (string) - required - starter|pro|enterprise.
  • payment_flow (string) - optional - direct or hosted (nowpayments).

Common Errors

  • 3001 - Invalid provider or plan
  • 4003 - Insufficient permissions

Example Request

{
  "plan_type": "pro",
  "provider": "stripe"
}

Example Response

{
  "checkout_url": "https://checkout.stripe.com/..."
}

Groups

GET /v1/groups List Groups

List all groups in the organization.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns groups.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Example Request

{}

Example Response

{
  "groups": [
    {
      "id": "grp_123",
      "name": "Document Team"
    }
  ]
}
POST /v1/groups Create Group

Create a named agent group for team broadcasts.

Auth

Bearer token or API key; tenant context required.

Success

201 - Group created.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • name (string) - required - Group name.
  • description (string) - optional - Optional description.
  • metadata (object) - optional - Custom fields.

Common Errors

  • 3001 - Invalid group payload

Example Request

{
  "description": "Writers and reviewers",
  "name": "Document Team"
}

Example Response

{
  "group": {
    "id": "grp_123",
    "name": "Document Team"
  }
}
DELETE /v1/groups/:id Delete Group

Delete a group and membership associations.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Group deleted.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Group ID in URL path.

Common Errors

  • 3001 - Group not found
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "status": "deleted"
}
GET /v1/groups/:id Get Group

Retrieve group details and members.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns group details.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Group ID in URL path.

Common Errors

  • 3001 - Group not found

Example Request

{}

Example Response

{
  "group": {
    "id": "grp_123",
    "members": [
      "writer-agent-1"
    ]
  }
}
PUT /v1/groups/:id Update Group

Update group name, description, and metadata.

Auth

Bearer token or API key; tenant context required.

Success

200 - Group updated.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Group ID in URL path.
  • name (string) - optional - New name.
  • description (string) - optional - New description.
  • metadata (object) - optional - Updated metadata.

Common Errors

  • 3001 - Invalid update payload

Example Request

{
  "name": "Document Team v2"
}

Example Response

{
  "group": {
    "id": "grp_123",
    "name": "Document Team v2"
  }
}
POST /v1/groups/:id/members Add Group Member

Attach an agent to a group.

Auth

Bearer token or API key; tenant context required.

Success

200 - Member added.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Group ID in URL path.
  • agent_id (string) - required - Agent ID to add.
  • role (string) - optional - Group role label.

Common Errors

  • 2001 - Agent not found

Example Request

{
  "agent_id": "reviewer-agent-1",
  "role": "reviewer"
}

Example Response

{
  "group_id": "grp_123",
  "status": "member_added"
}
DELETE /v1/groups/:id/members/:agent_id Remove Group Member

Detach an agent from a group.

Auth

Bearer token or API key; tenant context required.

Success

200 - Member removed.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Group ID in URL path.
  • agent_id (path) - required - Agent ID in URL path.

Common Errors

  • 3001 - Member not found

Example Request

{}

Example Response

{
  "status": "member_removed"
}
POST /v1/groups/:id/message Broadcast To Group

Send one message to all online/offline group members.

Auth

Bearer token or API key; tenant context required.

Success

202 - Broadcast accepted.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Group ID in URL path.
  • message (object) - required - CACP message payload.

Common Errors

  • 3001 - Invalid message payload

Example Request

{
  "message": {
    "message_id": "msg-2001",
    "message_type": "notification",
    "payload": {
      "content": "Deploy in 15 minutes"
    }
  }
}

Example Response

{
  "group_id": "grp_123",
  "status": "queued"
}

Messages

POST /v1/messages Send Message

Dispatch a protocol message for direct, broadcast, group, or capability routing.

Auth

Bearer token or API key; tenant context required.

Success

202 - Accepted and routed/queued.

Headers

  • Authorization: Bearer <jwt> OR X-API-Key: cacp_<key>
  • X-Organization-Id: <org_id>
  • Idempotency-Key: <optional key>

Body / Path Fields

  • message_id (string) - required - Client-generated unique id.
  • sender (object) - required - Sender identity.
  • recipient (object) - required - Routing target.
  • message_type (string) - required - Protocol message type. One of: conversation, task, rpc_request, rpc_response, rpc_error, capability_advertisement, heartbeat, control.
  • payload (object) - optional - Application payload.
  • metadata (object) - optional - Trace and custom metadata.

Common Errors

  • 3001 - Invalid message format (includes field-level details)
  • 2001 - Agent not found
  • 2008 - No matching agents
  • 6001 - Rate limit exceeded
  • 7001 - Insufficient funds

Example Request

{
  "message_id": "msg-1001",
  "message_type": "task",
  "payload": {
    "instruction": "review this draft"
  },
  "recipient": {
    "agent_id": "reviewer-agent-1",
    "discovery": "direct"
  },
  "sender": {
    "agent_id": "writer-agent-1"
  }
}

Example Response

{
  "cost_cents": 2,
  "message_id": "msg-1001",
  "recipients": [
    "reviewer-agent-1"
  ],
  "status": "delivered"
}
GET /v1/messages/:id Get Message

Retrieve message delivery status and metadata.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns message record.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Message ID in URL path.

Common Errors

  • 3001 - Invalid or unknown message id

Example Request

{}

Example Response

{
  "message": {
    "message_id": "msg-1001",
    "status": "delivered"
  }
}

Tasks

GET /v1/tasks List Tasks

List tasks with filter and pagination controls.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns task list.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Query Params

  • status (string) - optional - Filter status.
  • agent_id (string) - optional - Filter by recipient.
  • page (integer) - optional - Page number.
  • per_page (integer) - optional - Page size.

Example Request

{}

Example Response

{
  "tasks": [
    {
      "id": "task_123",
      "status": "queued"
    }
  ]
}
POST /v1/tasks Create Task

Create asynchronous work for one target agent.

Auth

Bearer token or API key; tenant context required.

Success

201 - Task queued.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • task_id (string) - optional - Optional custom task id.
  • task_type (string) - required - Task category.
  • recipient_agent_id (string) - required - Target agent.
  • payload (object) - required - Task payload.
  • priority (string) - optional - low|normal|high|critical.
  • scheduled_at (string) - optional - ISO8601 future execution.
  • max_retries (integer) - optional - Retry budget.
  • timeout_seconds (integer) - optional - Execution timeout.

Common Errors

  • 3001 - Invalid task payload

Example Request

{
  "payload": {
    "source": "s3://docs/input.md"
  },
  "priority": "high",
  "recipient_agent_id": "writer-agent-1",
  "task_type": "document.transform"
}

Example Response

{
  "status": "queued",
  "task_id": "task_123"
}
GET /v1/tasks/:id Get Task

Fetch one task by id.

Auth

Bearer token or API key; tenant context required.

Success

200 - Returns task details.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Task ID in URL path.

Common Errors

  • 3001 - Task not found

Example Request

{}

Example Response

{
  "task": {
    "id": "task_123",
    "status": "running"
  }
}
POST /v1/tasks/:id/cancel Cancel Task

Cancel a queued or running task.

Auth

Bearer token or API key; tenant context required. Minimum role: admin.

Success

200 - Cancellation accepted.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Task ID in URL path.

Common Errors

  • 3001 - Task cannot be cancelled
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "status": "cancelled",
  "task_id": "task_123"
}
POST /v1/tasks/:id/retry Retry Task

Requeue a failed task with existing payload.

Auth

Bearer token or API key; tenant context required.

Success

200 - Retry accepted.

Headers

  • Authorization or X-API-Key
  • X-Organization-Id

Body / Path Fields

  • id (path) - required - Task ID in URL path.

Common Errors

  • 3001 - Task cannot be retried

Example Request

{}

Example Response

{
  "status": "queued",
  "task_id": "task_123"
}

Webhooks (Payment Providers)

POST /webhooks/nowpayments NOWPayments Webhook

Inbound webhook for NOWPayments payment events. Note: there is no user-facing webhook management API (POST /v1/webhooks).

Auth

No JWT/API key. Signature hash validation required.

Success

200 - Returns processed or already_processed.

Headers

  • X-Nowpayments-Sig: <signed header>

Body / Path Fields

  • event (object) - required - NOWPayments payload.

Common Errors

  • 3001 - Invalid signature or payload

Example Request

{
  "payment_id": "np_1",
  "payment_status": "finished"
}

Example Response

{
  "status": "processed"
}
POST /webhooks/stripe Stripe Webhook

Inbound webhook for Stripe payment events. Note: there is no user-facing webhook management API (POST /v1/webhooks).

Auth

No JWT/API key. Request authenticity validated by Stripe signature.

Success

200 - Returns processed or already_processed.

Headers

  • Stripe-Signature: <signed header>

Body / Path Fields

  • event (object) - required - Stripe event payload.

Common Errors

  • 3001 - Invalid signature or payload

Example Request

{
  "id": "evt_1",
  "type": "invoice.payment_succeeded"
}

Example Response

{
  "status": "processed"
}

WebSocket And Channels

Connect to ws://localhost:4001/ws/v1, pass a JWT with agent_id and organization_id, then join topic agent:<agent_id>.

Inbound Events

  • send

    {"message": <CACP message object>}.

    Dispatches a protocol message over broker routing with rate/quota checks.

  • rpc_request

    {"message": <RPC request envelope>}.

    Initiates RPC processing; can return immediate response or async stream.

  • heartbeat

    {"timestamp": "ISO8601"} (payload optional).

    Refreshes connection liveness and returns heartbeat ack.

  • health_report

    {"metrics": {...}}.

    Submits agent health metrics captured by the health collector.

  • disconnect

    {"reason": "<text>"}.

    Graceful disconnect and agent unregister.

  • discover

    {"capability": "web_search", "framework": "langchain", "availability": "online", "limit": 10}.

    Query available agents by capability, framework, or availability. Returns list of matching agents.

  • presence_subscribe

    {"agent_ids": ["agent-1", "agent-2"]}.

    Subscribe to online/offline status updates for specific agents. Returns current status of subscribed agents.

  • presence_unsubscribe

    {"agent_ids": ["agent-1"]}.

    Unsubscribe from presence updates for specific agents.

  • task_create

    {"task": {"task_type": "...", "recipient_agent_id": "...", "payload": {...}}}.

    Create a new task via WebSocket. Returns task_id and status.

  • task_subscribe

    {"task_ids": ["task_123", "task_456"]}.

    Subscribe to real-time status updates for specific tasks.

  • task_unsubscribe

    {"task_ids": ["task_123"]}.

    Unsubscribe from task status updates.

  • queue_status

    {}.

    Query pending message queue status (total pending, by priority).

  • queue_subscribe

    {}.

    Subscribe to real-time queue change notifications (queued, delivered events).

  • queue_unsubscribe

    {}.

    Unsubscribe from queue update notifications.

  • rpc_status

    {"correlation_id": "corr-abc123"}.

    Query the status of an RPC request (pending, completed, failed, cancelled).

  • rpc_cancel

    {"correlation_id": "corr-abc123"}.

    Cancel a pending RPC request. Notifies both caller and responder.

  • group_create

    {"group": {"name": "Team A", "description": "...", "capabilities": [...]}}.

    Create a new agent group. Returns group_id and creation confirmation.

  • group_list

    {}.

    List all groups in the organization. Returns groups array with member counts.

  • group_info

    {"group_id": "grp_123"}.

    Get detailed group information including members list and metadata.

  • group_join

    {"group_id": "grp_123", "role": "member"}.

    Join a group as a member. Role defaults to 'member' if not specified.

  • group_leave

    {"group_id": "grp_123"}.

    Leave a group. Removes agent from group membership.

  • group_broadcast

    {"group_id": "grp_123", "message": {...}, "exclude_sender": true}.

    Send a message to all online group members. Optionally exclude sender.

  • group_subscribe

    {"group_ids": ["grp_123", "grp_456"]}.

    Subscribe to real-time group updates (member join/leave, group changes).

  • group_unsubscribe

    {"group_ids": ["grp_123"]}.

    Unsubscribe from group update notifications.

  • balance_subscribe

    {}.

    Subscribe to real-time balance and billing updates for the agent's organization.

  • balance_unsubscribe

    {}.

    Unsubscribe from balance and billing updates.

  • audit_subscribe

    {"action_filter": ["message.sent"], "resource_type_filter": ["message"]}.

    Subscribe to real-time audit events for the agent's organization. Optional filters for action and resource type.

  • audit_unsubscribe

    {}.

    Unsubscribe from audit events.

  • alert_subscribe

    {"severity_filter": ["critical", "warning"], "type_filter": ["rate_limit"]}.

    Subscribe to real-time alerts for the agent's organization. Optional filters for severity and alert type.

  • alert_unsubscribe

    {}.

    Unsubscribe from alerts.

Outbound Events

  • ack

    Message acceptance and delivery metadata.

  • message

    Broker-delivered inbound protocol message.

  • error

    Protocol or validation failure details with numeric code.

  • rpc_response

    Immediate RPC result.

  • rpc_error

    RPC failure details.

  • rpc_chunk

    Streaming chunk for long-running RPC.

  • rpc_cancelled

    RPC cancellation notification to caller.

  • heartbeat

    Liveness confirmation.

  • health_check_request

    Server-initiated health probe.

  • health_report_ack

    Health report persistence acknowledgement.

  • discover

    Response with list of discovered agents matching query filters.

  • presence_subscribe

    Confirmation of presence subscription with current agent statuses.

  • presence_unsubscribe

    Confirmation of presence unsubscription.

  • presence_update

    Push notification when a subscribed agent's status changes (online/offline).

  • delivered

    Push notification when a sent message is delivered to the recipient's WebSocket connection.

  • task_create

    Confirmation of task creation with task_id and initial status.

  • task_subscribe

    Confirmation of task subscription with subscribed task_ids.

  • task_unsubscribe

    Confirmation of task unsubscription.

  • task_update

    Push notification when a subscribed task's status changes (pending, running, completed, failed, cancelled).

  • queue_status

    Response with pending message queue statistics.

  • queue_subscribe

    Confirmation of queue update subscription.

  • queue_unsubscribe

    Confirmation of queue unsubscription.

  • queue_update

    Push notification when messages are queued or delivered (queued, delivered events).

  • rpc_status

    Response with RPC request status (pending, completed, failed, cancelled, not_found).

  • rpc_cancel

    Confirmation of RPC cancellation request.

  • rpc_cancel_notification

    Push notification to RPC responder when request is cancelled by caller.

  • group_create

    Confirmation of group creation with group_id and name.

  • group_list

    Response with list of groups in the organization.

  • group_info

    Response with detailed group information including members.

  • group_join

    Confirmation of group join with role and joined_at timestamp.

  • group_leave

    Confirmation of group leave.

  • group_broadcast

    Confirmation of broadcast with recipient count and list.

  • group_subscribe

    Confirmation of group subscription with subscribed group_ids.

  • group_unsubscribe

    Confirmation of group unsubscription.

  • group_update

    Push notification for group events: member_joined, member_left, group_updated, group_deleted.

  • balance_subscribe

    Confirmation of balance subscription with organization_id.

  • balance_unsubscribe

    Confirmation of balance unsubscription.

  • billing_update

    Push notification for billing events: balance_update, usage_alert, transaction.

  • audit_subscribe

    Confirmation of audit subscription with optional filters.

  • audit_unsubscribe

    Confirmation of audit unsubscription.

  • audit_event

    Push notification for audit events matching subscription filters.

  • alert_subscribe

    Confirmation of alert subscription with optional filters.

  • alert_unsubscribe

    Confirmation of alert unsubscription.

  • alert

    Push notification for alerts matching subscription filters.

Dashboard Guide

Path Page Purpose
/dashboard Overview Global health and usage summary.
/dashboard/agents Agents Registry, status, and capabilities.
/dashboard/messages Messages Recent message traffic and status.
/dashboard/api-playground API Playground Interactive HTTP API testing.
/dashboard/websocket-playground WS Playground Interactive channel testing.
/dashboard/health Health Agent and system health metrics.
/dashboard/analytics Analytics Usage, trends, and KPIs.
/dashboard/alerts Alerts Threshold and anomaly alerting.
/dashboard/team Team Users, membership, and roles.
/dashboard/settings Settings Organization and key configuration.
/dashboard/billing Billing Credits, subscriptions, invoices.
/dashboard/retention Data Retention Data cleanup policies and metrics.

Architecture

  • ConnectionManager: tracks connected sockets and heartbeats.
  • AgentRegistry: ETS-backed capability and availability registry.
  • MessageRouter + Dispatcher: resolves routing and persistence.
  • RPC: request/response orchestration including streaming and cancellation.
  • RateLimiter: request and message throughput controls.
  • Presence: opt-in agent presence subscriptions and status tracking.
  • DeliveryTracker: message delivery confirmation and status tracking.
  • TaskTracker: task subscription management for real-time status updates.
  • QueueTracker: offline queue subscription management for real-time notifications.
  • GroupTracker: group subscription management for real-time member updates.
  • BillingTracker: billing subscription management for balance and usage alerts.
  • AuditTracker: audit log subscription management for compliance monitoring.
  • AlertTracker: alert subscription management for operational notifications.
  • TaskQueue + OfflineQueue: DB-backed asynchronous delivery.
  • Usage.Meter + Billing modules: metering, credits, and subscriptions.
  • HealthCollector + HealthMetrics + Alerting.Engine: health telemetry and alarms.
  • Analytics.Aggregator: usage and operational analytics.
  • Authorization.Policy: role-based permission enforcement for team and billing operations.
  • Retention: automatic data cleanup for usage events and messages.

Data Model

  • organizations: tenant boundary and plan settings.
  • users and api_keys: dashboard auth and key-based integration auth.
  • agents: registered agent identity + capabilities.
  • messages and offline_messages: protocol message persistence.
  • tasks: queued async jobs and state transitions.
  • agent_groups and group memberships: team routing.
  • usage_events: billing/metering ledger.
  • subscriptions, payment_methods, invoices, credits: billing entities.
  • audit_logs: compliance trail.
  • agent_health_metrics and alerts: reliability monitoring.

Data Retention

CACP automatically cleans up old data to prevent unbounded database growth, ensuring predictable storage costs and query performance.

Retention Policies

Data Type Default Retention Cleanup Frequency Config Notes
Usage Events 30 days Hourly RETENTION_USAGE_EVENTS_DAYS All usage events older than the retention threshold are deleted.
Messages 90 days Daily RETENTION_MESSAGES_DAYS Messages older than the retention threshold are deleted. Pending and queued messages are preserved regardless of age.

Configuration

Environment Variable Default Description
RETENTION_USAGE_EVENTS_DAYS 30 Number of days to keep usage events.
RETENTION_MESSAGES_DAYS 90 Number of days to keep messages.
RETENTION_MESSAGES_CLEANUP_ENABLED true Enable or disable message cleanup (set to 'false' to preserve all messages).

Dashboard

Monitor retention metrics at /dashboard/retention:

  • View total record counts for usage events and messages
  • See data age distribution (1 day, 7 days, 30 days, 90 days, 180 days, 1 year)
  • View messages by status breakdown
  • Monitor last cleanup timestamps
  • Trigger manual cleanup operations
  • View total deleted record counts

Manual Cleanup

Trigger immediate cleanup via the dashboard or programmatically in IEx console.

Cacp.Retention.force_cleanup(:usage_events) - Delete expired usage events
Cacp.Retention.force_cleanup(:messages) - Delete expired messages (preserves pending/queued)

AI Agent Guide

  • Use deterministic message_id and optional idempotency key for retries.
  • Always include trace metadata (correlation_id, workflow id, retry count).
  • Treat 6001, 6002, and 7001 as backoff or funding signals.
  • For long operations, prefer task endpoints or streaming RPC chunks.
  • Use groups/capabilities for adaptive routing instead of hardcoding recipient ids.

Integrations

LangChain

Map tools/chains to CACP messages and use capability tags for specialized agents.

AutoGen

Use one channel topic per AutoGen agent; map conversation turns to `message_type` values.

CrewAI

Represent crew roles as CACP groups and route team tasks through group broadcasts.

Errors And Troubleshooting

Code Reason Surface
2001 Agent not found HTTP + WS
2008 No matching agents HTTP + WS
3001 Invalid request payload HTTP + WS
4001 Authentication required HTTP
4003 Insufficient permissions HTTP
5003 Missing organization context HTTP + WS
6001 Rate limit exceeded HTTP + WS
6002 Quota exceeded WS
7001 Insufficient funds HTTP + WS
  • 401/403-like failures: verify JWT validity, claims, and org context.
  • 429/6001: back off and honor reset headers; smooth burst traffic.
  • No recipients: validate direct IDs, capability names, and group membership.
  • Webhook failures: confirm provider signature secret and raw body handling.