🤖 Agent Hub - Technical API Documentation

Version 1.0 RESTful API Socket.IO Python Flask

1. Overview

Agent Hub is a lightweight distributed AI agent orchestrator designed for multi-machine deployments across NAT boundaries. The system enables seamless communication between autonomous AI agents regardless of network topology.

Core Components:

2. Architecture

The architecture follows a hub-and-spoke model with outbound-only connections to traverse NAT/firewalls.

[Agent] --(outbound WS)--> [Hub Server] <--(outbound WS)-- [Agent]
                  \                          /
                   \                        /
                    ---[Message Queue]-----

Network Topology:

Component Role Connection Type
Hub Server Maintenance of inbound listening port (TCP 5000 default) ServeWSI
Connected Agents Initiate outbound connections to Hub Outbound WebSocket
External APIs Optional ngrok tunneling for reverse proxy TCP Tunnel

3. Protocol Specification

3.1 Connection Handshake

POST /api/v1/connect
Content-Type: application/json

{
    "agent_id": "string",          // Unique agent identifier
    "agent_name": "string",        // Human-readable name
    "capabilities": ["array"],     // Array of supported capabilities
    "version": "string",           // Client version
    "metadata": {}                 // Optional key-value pairs
}

3.2 Real-time Events

All events are transmitted via Socket.IO:

Event Direction Description Payload Schema
agents:connect Agent → Hub New agent joins network {agent_id, timestamp}
agents:disconnect Agent → Hub Agent leaves gracefully {agent_id, reason}
messages:broadcast Hub → All Message to all connected agents {message, sender_id, priority}
messages:direct Hub → Target Point-to-point message {to_agent_id, message, sender_id}
queue:push Hub → Offline Task queued for offline agent {task, agent_id, expiry}
files:transfer Bidirectional Binary file transfer {file_id, chunk, metadata}

3.3 Message Schema

{
    "msg_id": "uuid",              // Unique message identifier
    "timestamp": "ISO8601",        // UTC timestamp
    "sender_id": "agent_uuid",     // Source agent ID
    "type": "command|data|heartbeat|status",
    "payload": {},                 // Message-specific payload
    "priority": 0,                 // Priority level (0-10)
    "ttl": null                    // Time-to-live in seconds
}

4. REST API Endpoints

4.1 Health & Status

Endpoint Method Description Response
/api/v1/health GET Server health check {"status": "ok", "uptime": 12345}
/api/v1/status GET Current network status {"active_agents": 5, "queued_tasks": 2}
/api/v1/agents GET List all registered agents [{"agent_id": "...", ...}]

4.2 Task Management

Endpoint Method Description Response
/api/v1/tasks POST Create new task for specific agent {"task_id": "uuid"}
/api/v1/tasks/broadcast POST Broadcast task to all agents {"task_id": "uuid", "targets": [...]}
/api/v1/queue GET Pending tasks for offline agents [{"task_id": "...", ...}]

4.3 File Operations

Endpoint Method Description Response
/api/v1/files/upload POST Upload file to hub {"file_url": "..."}
/api/v1/files/{file_id}/download GET Retrieve uploaded file File stream

5. Security Configuration

Authentication Methods:

  1. Token-based: Bearer token in HTTP headers
  2. API Key: X-API-Key header
  3. JWT: JSON Web Tokens for session management

Recommended Headers:

X-Agent-ID: required
X-API-Key: optional
Authorization: Bearer <jwt_token>

Cross-Origin Resource Sharing (CORS):

CORS allowed origins configurable via environment variable
CORS_ORIGINS=https://example.com,https://admin.example.com

6. Deployment Examples

6.1 Basic Setup (Flask Development)

$ git clone https://github.com/IvanDeus/agent-hub-py.git
$ cd agent-hub-py
$ pip install flask flask-socketio
$ python app.py

6.2 Production with Ngrok (HTTPS)

# Start hub server locally
$ python app.py

# Open ngrok tunnel (separate terminal)
$ ngrok http 5000

# Connect agents using ngrok URL
$ python client.py --hub-url wss://abc123.ngrok.io

6.3 Docker Containerization

Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]

7. Client Integration Guide

7.1 Minimal Implementation (client.py)

import socketio
from uuid import uuid4

sio = socketio.Client()

@sio.event
def connect():
    print("Connected to Agent Hub")
    sio.emit('agents:connect', {'agent_id': str(uuid4())})

@sio.on('messages:direct')
def handle_message(data):
    print(f"Received: {data}")
    # Process message logic here

if __name__ == '__main__':
    sio.connect('wss://your-hub.example.com')
    sio.wait()

7.2 Required Modules:

8. Rate Limits & Throttling

Default rate limits per agent:

Operation Limit Window
Messages sent 100 per minute
File transfers 10 per hour
Connection attempts 5 per minute

Error Responses:

{
    "error": "rate_limit_exceeded",
    "retry_after": 60,
    "limit": 100,
    "current": 101
}

9. Monitoring & Observability

Metrics Exported:

Health Check Endpoints:

/health/zombies - Check for stale connections
/health/metrics - Prometheus metrics endpoint
/health/ready - Readiness probe for orchestration

10. Troubleshooting

Common Issues:

Connection Failures:

Message Delivery Issues:

NAT Traversal Problems:

11. Version History

Version Date Changes
1.0.0 2024-10 Initial release with Socket.IO support

Resources

Contact & Support:

For technical issues or feature requests: Open an issue on GitHub repository.

This documentation is machine-readable and optimized for search engine indexing. Last updated: October 2026.