> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Server Module

> HTTP server with SSE event streaming for real-time agent communication

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(name="server-agent", instructions="Serve agent requests over HTTP.")
agent.start("Start the agent server on port 8080.")
```

Expose agents over HTTP with Server-Sent Events so clients receive live updates without polling.

The user connects a web client; the agent server streams SSE events while the agent processes each HTTP request.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    Client[🌐 Client] -->|REST| Server[🛰️ AgentServer]
    Server -->|SSE /events| Client
    Server --> Agent[🤖 Agent run]
    Agent --> Server

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef tool fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef ok fill:#10B981,stroke:#7C90A0,color:#fff
    class Agent agent
    class Server tool
    class Client ok

```

## How It Works

A client subscribes to the event stream, and the server pushes agent updates live as work progresses.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Client
    participant AgentServer
    participant Agent

    User->>Client: Open connection
    Client->>AgentServer: GET /events (SSE)
    AgentServer->>Agent: Run task
    Agent-->>AgentServer: Progress events
    AgentServer-->>Client: Stream updates
    Client-->>User: Live results
```

## Features

* **REST API** - HTTP endpoints for agent operations
* **SSE Streaming** - Real-time event streaming to clients
* **CORS Support** - Configurable cross-origin settings
* **Multi-client** - Handle multiple concurrent connections

## Quick Start

<Steps>
  <Step title="Start a server">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents.server import AgentServer, ServerConfig

    config = ServerConfig(host="0.0.0.0", port=8080, cors_origins=["http://localhost:3000"])
    server = AgentServer(config=config)
    server.start()
    server.broadcast("message", {"text": "Hello clients!"})
    ```
  </Step>

  <Step title="Use as a context manager">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents.server import AgentServer

    with AgentServer(port=8080) as server:
        server.broadcast("status", {"ready": True})
    # Server stops automatically on exit
    ```
  </Step>
</Steps>

## API Reference

### ServerConfig

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
@dataclass
class ServerConfig:
    host: str = "127.0.0.1"
    port: int = 8765
    cors_origins: List[str] = ["*"]
    auth_token: Optional[str] = None
    max_connections: int = 100
```

### AgentServer

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
class AgentServer:
    def start(self, blocking: bool = False) -> None:
        """Start the server."""
    
    def stop(self) -> None:
        """Stop the server and disconnect clients."""
    
    def broadcast(self, event_type: str, data: Dict) -> None:
        """Broadcast event to all connected clients."""
    
    @property
    def is_running(self) -> bool:
        """Check if server is running."""
    
    @property
    def client_count(self) -> int:
        """Get number of connected clients."""
```

## HTTP Endpoints

| Endpoint   | Method | Description              |
| ---------- | ------ | ------------------------ |
| `/health`  | GET    | Health check             |
| `/info`    | GET    | Server information       |
| `/events`  | GET    | SSE event stream         |
| `/publish` | POST   | Publish event to clients |

## Examples

### Context Manager

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents.server import AgentServer

with AgentServer(port=8080) as server:
    # Server is running
    server.broadcast("status", {"ready": True})
    
    # Do work...
    
# Server automatically stopped
```

### Event Handler

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
server = AgentServer()

@server.on_event("message")
def handle_message(data):
    print(f"Received: {data}")

server.start()
```

### Client Connection (JavaScript)

```javascript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
const eventSource = new EventSource('http://localhost:8765/events');

eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
};

eventSource.addEventListener('message', (event) => {
    console.log('Message event:', JSON.parse(event.data));
});
```

### Publishing Events

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Publish via HTTP
curl -X POST http://localhost:8765/publish \
  -H "Content-Type: application/json" \
  -d '{"type": "notification", "data": {"text": "Hello!"}}'
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Restrict CORS in production">
    Replace `cors_origins=["*"]` with explicit front-end origins before exposing the server publicly.
  </Accordion>

  <Accordion title="Set auth_token for remote clients">
    Use `ServerConfig(auth_token=...)` when the server binds outside loopback so `/publish` cannot be abused.
  </Accordion>

  <Accordion title="Prefer SSE for progress, REST for commands">
    Stream long agent runs on `/events`; submit work via REST and broadcast milestones to connected clients.
  </Accordion>

  <Accordion title="Monitor client_count during load tests">
    Watch `server.client_count` and tune `max_connections` before production traffic spikes.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card icon="rocket" href="/features/async-jobs" title="Async Jobs">
    Submit long-running work and poll or stream results via the jobs API.
  </Card>

  <Card icon="server" href="/features/agent-api-launch" title="Agent API Launch">
    Launch agents as HTTP services with minimal setup.
  </Card>
</CardGroup>
