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>

Official SDK Libraries

Production-ready SDKs for your favorite languages and frameworks. All repositories are open source under Apache 2.0.

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) Quick Start for Agents: Register agent with `POST /v1/agents` to get API key + auto-created org. Use API key for HTTP and WebSocket connections.
  4. 4) Traditional User Flow: Register organization with `POST /v1/auth/register`, get JWT, use for HTTP/API keys.
  5. 5) Register first agent: `POST /v1/agents` with agent_id and capabilities.
  6. 6) Send first message: `POST /v1/messages` with message payload.
  7. 7) Connect WebSocket at `ws://localhost:4001/ws/v1?token=<api_key>` 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 using simple API key authentication.

1

Register Agent

Register your agent directly. This endpoint auto-creates an organization for you and returns a long-lived API key. No manual organization setup required.

Endpoint: POST /v1/agents

Request Body:

{
  "agent_id": "my-agent-001",
  "capabilities": [
    "content_generation",
    "summarization"
  ],
  "framework": "langchain"
}

Response:

{
  "agent_id": "my-agent-001",
  "api_key": "cacp_live_abc123def456...",
  "organization_id": "org_xyz789",
  "registered": true,
  "registered_at": "2024-01-15T10:30:00Z"
}

Note: Save the api_key - it's only shown once! This API key works for both HTTP and WebSocket (no expiration).

2

Make HTTP Requests

Use the API key to make authenticated HTTP requests. Provide it in the X-API-Key header or as a Bearer token.

Endpoint: Any authenticated endpoint

Headers:

X-API-Key: cacp_live_abc123def456...

Content-Type: application/json

Example:

Endpoint: POST /v1/agents/discover

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

Response:

{
  "agents": [
    {
      "agent_id": "writer-agent-1",
      "score": 0.98
    }
  ],
  "query": "agent that can write release notes",
  "total": 1
}

Note: You can also use 'Authorization: Bearer cacp_live_abc123def456...' if preferred.

3

Connect via WebSocket

Connect to the WebSocket endpoint using your API key. No JWT exchange required - just pass the API key as the token parameter.

Endpoint: ws://localhost:4001/ws/v1?token=cacp_live_abc123def456...

Example:

{
  "join_message": {
    "event": "phx_join",
    "ref": 1,
    "topic": "agent:my-agent-001"
  },
  "send_example": {
    "event": "send",
    "payload": {
      "message": {
        "message_id": "msg-1001",
        "message_type": "conversation",
        "payload": {
          "text": "Hello!"
        },
        "recipient": {
          "agent_id": "reviewer-agent-1",
          "discovery": "direct"
        },
        "sender": {
          "agent_id": "my-agent-001"
        }
      }
    },
    "topic": "agent:my-agent-001"
  }
}

Note: WebSocket connections accept API keys directly in the URL token parameter.

Authentication Options

Method Header Format Use Case Expiry
API Key (Recommended) X-API-Key: cacp_<key> or Authorization: Bearer cacp_<key> Simple, long-lived authentication for both HTTP and WebSocket Never expires (long-lived)
JWT Token (Legacy) Authorization: Bearer <jwt> Traditional web applications with session-based authentication Configurable (expires, requires refresh)

Common Endpoints

Method Path Auth Purpose
POST /v1/agents None (self-registration) Register agent + get API key
POST /v1/agents/:id/api-keys API key or JWT Generate new API key
GET /v1/agents/:id/api-keys API key or JWT List API keys (masked)
DELETE /v1/agents/:id/api-keys/:key_id API key or JWT Revoke API key
POST /v1/messages API key or JWT Send message
GET /v1/agents/query API key or JWT Query agents by capability

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": [
    {
      "created_at": "2024-01-15T10:30:00Z",
      "expires_at": null,
      "id": "key_123",
      "last_used_at": "2024-01-20T14:22:00Z",
      "name": "Production Agent Key",
      "scopes": [
        "messages:send",
        "agents:read"
      ]
    }
  ],
  "total": 1
}
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_in_days (integer) - optional - Optional number of days until expiration.

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

204 - 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

  • 2001 - API key not found

Example Request

{}

Example Response

{}
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

  • 2001 - API key not found

Example Request

{}

Example Response

{
  "created_at": "2024-01-15T10:30:00Z",
  "expires_at": null,
  "id": "key_123",
  "last_used_at": "2024-01-20T14:22:00Z",
  "name": "Production Agent Key",
  "scopes": [
    "messages:send",
    "agents:read"
  ]
}

Agent API Keys

GET /v1/agents/:id/api-keys List API Keys

List all API keys for an agent. Key values are masked for security.

Auth

API key or JWT; tenant context required.

Success

200 - Returns list of masked API keys.

Headers

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

Body / Path Fields

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

Example Request

{}

Example Response

{
  "agent_id": "writer-agent-1",
  "api_keys": [
    {
      "expires_at": null,
      "id": "uuid-123",
      "inserted_at": "2024-01-15T10:30:00Z",
      "key_prefix": "live_abc123",
      "last_used_at": "2024-01-20T14:22:00Z",
      "masked_key": "cacp_live_abc123**************************",
      "name": "Production Key",
      "scopes": []
    }
  ],
  "total": 1
}
POST /v1/agents/:id/api-keys Generate API Key

Generate a new API key for an agent. API keys are long-lived and work for both HTTP and WebSocket.

Auth

API key or JWT; tenant context required.

Success

201 - API key generated.

Headers

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

Body / Path Fields

  • id (path) - required - Agent ID in URL path.
  • name (string) - optional - Key name (default: 'API Key').
  • scopes (array<string>) - optional - Permission scopes.

Common Errors

  • 5004 - API key not found

Example Request

{
  "name": "Production Key",
  "scopes": []
}

Example Response

{
  "agent_id": "writer-agent-1",
  "api_key": "cacp_live_abc123def456...",
  "created_at": "2024-01-15T10:30:00Z"
}
DELETE /v1/agents/:id/api-keys/:key_id Revoke API Key

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

Auth

API key or JWT; tenant context required.

Success

204 - API key revoked successfully.

Headers

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

Body / Path Fields

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

Common Errors

  • 5004 - API key not found

Example Request

{}

Example Response

{}

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.
  • framework (string) - optional - Filter by framework.
  • availability (string) - optional - Filter by availability status.
  • organization_id (string) - optional - Filter by organization ID.

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. Returns a long-lived API key for immediate use. Auto-creates organization if organization_id not provided.

Auth

None (self-registration endpoint). Auto-creates organization if not associated.

Success

201 - Agent registered with API key for immediate use.

Headers

  • X-Organization-Id: <org_id> (optional, associate with existing org)

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.
  • organization_id (string) - optional - Optional organization ID to join. If omitted, a new organization is auto-created.

Common Errors

  • 3001 - Invalid registration payload
  • 2001 - Organization not found (when organization_id is provided)

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",
  "api_key": "cacp_live_abc123def456...",
  "organization_id": "org_xyz789",
  "registered": true,
  "registered_at": "2024-01-15T10:30:00Z"
}
DELETE /v1/agents/:id Delete Agent

Remove an agent registration.

Auth

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

Success

204 - 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

{}
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_id": "writer-agent-1",
  "agent_type": "service",
  "availability": "online",
  "capabilities": [
    "summarization",
    "drafting"
  ],
  "framework": "langchain",
  "organization_id": "org_xyz789"
}
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 - Missing required fields: query

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"
    }
  ],
  "pagination": {
    "page": 1,
    "per_page": 50,
    "total": 100,
    "total_pages": 2
  }
}
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

  • 9001 - Audit log not found

Example Request

{}

Example Response

{
  "action": "agent.registered",
  "actor_id": "writer-agent-1",
  "actor_type": "agent",
  "created_at": "2024-01-15T10:30:00Z",
  "details": null,
  "id": "log_1",
  "ip_address": null,
  "resource_id": "writer-agent-1",
  "resource_type": "agent"
}
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 (content-type: text/csv).

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

"id,actor_type,actor_id,action,resource_type,resource_id,ip_address,created_at\n..."

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

{
  "organization_id": "org_456",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "email": "alice@acme.com",
    "id": "user_123",
    "name": "Alice Smith",
    "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",
    "plan_type": "free"
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "email": "alice@acme.com",
    "id": "user_123",
    "name": "Alice Smith",
    "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"
  }
}

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

{
  "count": 1,
  "groups": [
    {
      "capabilities": [],
      "created_at": "2024-01-15T10:30:00Z",
      "description": "Writers and reviewers",
      "group_id": "grp_123",
      "leader_agent_id": null,
      "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

  • group_id (string) - optional - Optional custom group ID.
  • name (string) - required - Group name.
  • description (string) - optional - Optional description.
  • leader_agent_id (string) - optional - Leader agent ID.
  • capabilities (array<string>) - optional - Group capabilities.
  • metadata (object) - optional - Custom fields.

Common Errors

  • 7001 - Invalid group parameters
  • 7008 - Group with this group_id already exists

Example Request

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

Example Response

{
  "created_at": "2024-01-15T10:30:00Z",
  "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

  • 7003 - Group not found
  • 4003 - Insufficient permissions

Example Request

{}

Example Response

{
  "group_id": "grp_123",
  "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

  • 7003 - Group not found

Example Request

{}

Example Response

{
  "capabilities": [],
  "created_at": "2024-01-15T10:30:00Z",
  "description": "Writers and reviewers",
  "group_id": "grp_123",
  "leader_agent_id": null,
  "member_count": 1,
  "members": [
    {
      "agent_id": "writer-agent-1",
      "joined_at": "2024-01-15T10:30:00Z",
      "role": "member"
    }
  ],
  "metadata": {},
  "name": "Document Team",
  "updated_at": "2024-01-15T10:30:00Z"
}
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.
  • leader_agent_id (string) - optional - New leader agent ID.
  • capabilities (array<string>) - optional - Updated capabilities.
  • metadata (object) - optional - Updated metadata.

Common Errors

  • 7003 - Group not found
  • 7004 - Invalid update parameters

Example Request

{
  "name": "Document Team v2"
}

Example Response

{
  "group_id": "grp_123",
  "name": "Document Team v2",
  "updated_at": "2024-01-15T12:00:00Z"
}
POST /v1/groups/:id/members Add Group Member

Attach an agent to a group.

Auth

Bearer token or API key; tenant context required.

Success

201 - 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

  • 7003 - Group not found
  • 7005 - Agent not found
  • 7006 - Failed to add member

Example Request

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

Example Response

{
  "agent_id": "reviewer-agent-1",
  "joined_at": "2024-01-15T10:30:00Z",
  "role": "reviewer"
}
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

  • 7003 - Group not found

Example Request

{}

Example Response

{
  "agent_id": "reviewer-agent-1",
  "group_id": "grp_123",
  "status": "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

  • 7003 - Group not found
  • 7007 - No online members in group

Example Request

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

Example Response

{
  "group_id": "grp_123",
  "recipient_count": 2,
  "recipients": [
    "writer-agent-1",
    "reviewer-agent-1"
  ],
  "status": "broadcast_sent"
}

Health

GET /health Health Check

Check if the broker service is running and healthy.

Auth

None

Success

200 - Service is healthy.

Example Request

{}

Example Response

{
  "status": "ok",
  "timestamp": 1704000000000
}

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"
  ],
  "remaining_balance_cents": 998,
  "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.
  • priority (string) - optional - Filter priority.
  • sender_agent_id (string) - optional - Filter by sender.
  • recipient_agent_id (string) - optional - Filter by recipient.

Example Request

{}

Example Response

{
  "count": 1,
  "tasks": [
    {
      "completed_at": null,
      "created_at": "2024-01-15T10:30:00Z",
      "priority": "high",
      "recipient_agent_id": "reviewer-agent-1",
      "scheduled_at": null,
      "sender_agent_id": "writer-agent-1",
      "started_at": null,
      "status": "queued",
      "task_id": "task_123",
      "task_type": "document.transform"
    }
  ]
}
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

  • 6001 - Invalid task parameters
  • 6008 - Task with this task_id already exists

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

  • 6002 - Task not found

Example Request

{}

Example Response

{
  "completed_at": null,
  "created_at": "2024-01-15T10:30:00Z",
  "error_message": null,
  "max_retries": 3,
  "payload": {
    "source": "s3://docs/input.md"
  },
  "priority": "high",
  "recipient_agent_id": "reviewer-agent-1",
  "result": null,
  "retry_count": 0,
  "scheduled_at": null,
  "sender_agent_id": "writer-agent-1",
  "started_at": "2024-01-15T10:31:00Z",
  "status": "running",
  "task_id": "task_123",
  "task_type": "document.transform",
  "updated_at": "2024-01-15T10:31:00Z"
}
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

  • 6002 - Task not found
  • 6004 - Cannot cancel a completed task
  • 6005 - Failed to cancel task

Example Request

{}

Example Response

{
  "cancelled_at": "2024-01-15T11:00:00Z",
  "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

  • 6002 - Task not found
  • 6006 - Task cannot be retried
  • 6007 - Failed to retry task

Example Request

{}

Example Response

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

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/agents/:agent_id Agent Details Detailed view of a single agent.
/dashboard/messages Messages Recent message traffic and status.
/dashboard/tasks Tasks Async work items and status tracking.
/dashboard/groups Groups Agent groups and membership management.
/dashboard/audit Audit Security and activity event log.
/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.
  • AgentGroups: group management for team routing and broadcast.
  • MessageRouter: resolves agent routing.
  • Messaging.Dispatcher: message delivery orchestration.
  • 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
3002 Missing required fields HTTP
4001 Authentication required HTTP
4003 Insufficient permissions HTTP
4004 RPC request not found HTTP + WS
5001 Authentication required HTTP
5002 Invalid API key HTTP
5003 Missing organization context HTTP + WS
5004 User not found HTTP
5005 Account disabled HTTP
5006 Invalid token HTTP
6001 Invalid task parameters HTTP
6002 Task not found HTTP
6003 Failed to list tasks HTTP
6004 Cannot cancel a completed task HTTP
6005 Failed to cancel task HTTP
6006 Task cannot be retried HTTP
6007 Failed to retry task HTTP
6008 Task with this task_id already exists HTTP
7001 Insufficient funds HTTP + WS
7002 Failed to list groups HTTP
7003 Group not found HTTP + WS
7004 Invalid update parameters HTTP
7005 Agent not found HTTP
7006 Failed to add member HTTP
7007 No online members in group HTTP
7008 Group with this group_id already exists HTTP
9001 Audit log not found HTTP
  • 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.