# BZZZ MCP Server API Reference

Complete API reference for all components and interfaces in the BZZZ MCP Server.

## Table of Contents

- [MCP Tools](#mcp-tools)
- [Agent Management](#agent-management)
- [Conversation Management](#conversation-management)
- [P2P Connector](#p2p-connector)
- [OpenAI Integration](#openai-integration)
- [Cost Tracker](#cost-tracker)
- [Configuration](#configuration)
- [Error Handling](#error-handling)

## MCP Tools

### bzzz_announce

Announce agent presence and capabilities on the BZZZ network.

**Parameters:**
- `agent_id` (string, required): Unique identifier for the agent
- `role` (string, required): Agent's primary role (architect, reviewer, documentation, etc.)
- `capabilities` (string[], optional): List of agent capabilities
- `specialization` (string, optional): Agent's area of expertise
- `max_tasks` (number, optional, default: 3): Maximum concurrent tasks

**Response:**
```json
{
  "success": true,
  "message": "Agent architect-001 (architect) announced to BZZZ network",
  "agent": {
    "id": "architect-001",
    "role": "architect",
    "capabilities": ["system_design", "architecture_review"],
    "specialization": "distributed_systems",
    "status": "idle"
  }
}
```

**Errors:**
- Missing required fields (`agent_id`, `role`)
- Agent ID already exists
- Network communication failure

### bzzz_lookup

Discover agents and resources using semantic addressing.

**Parameters:**
- `semantic_address` (string, required): BZZZ semantic address in format `bzzz://agent:role@project:task/path`
- `filter_criteria` (object, optional): Additional filtering options
  - `expertise` (string[]): Required expertise areas
  - `availability` (boolean): Only available agents
  - `performance_threshold` (number): Minimum performance score (0-1)

**Address Components:**
- `agent`: Specific agent ID or `*` for any
- `role`: Agent role or `*` for any
- `project`: Project identifier or `*` for any
- `task`: Task identifier or `*` for any
- `path`: Optional resource path

**Response:**
```json
{
  "success": true,
  "address": "bzzz://*:architect@myproject:api_design",
  "parsed_address": {
    "agent": null,
    "role": "architect",
    "project": "myproject",
    "task": "api_design",
    "path": null,
    "raw": "bzzz://*:architect@myproject:api_design"
  },
  "matches": [
    {
      "id": "architect-001",
      "role": "architect",
      "capabilities": ["system_design", "api_design"],
      "available": true,
      "performance": 0.95,
      "score": 85
    }
  ],
  "count": 1,
  "query_time": "2025-08-09T16:22:20Z"
}
```

### bzzz_get

Retrieve content from BZZZ semantic addresses.

**Parameters:**
- `address` (string, required): BZZZ semantic address
- `include_metadata` (boolean, optional, default: true): Include resource metadata
- `max_history` (number, optional, default: 10): Maximum historical entries

**Response:**
```json
{
  "success": true,
  "address": "bzzz://architect-001:architect@myproject:api_design",
  "content": {
    "agent_info": {
      "id": "architect-001",
      "role": "architect",
      "status": "idle",
      "performance": 0.95
    },
    "recent_activity": [...],
    "current_tasks": [...]
  },
  "metadata": {
    "last_updated": "2025-08-09T16:22:20Z",
    "content_type": "agent_data",
    "version": "1.0"
  },
  "retrieved_at": "2025-08-09T16:22:20Z"
}
```

### bzzz_post

Post events or messages to BZZZ addresses.

**Parameters:**
- `target_address` (string, required): Target BZZZ address
- `message_type` (string, required): Type of message being sent
- `content` (object, required): Message content
- `priority` (string, optional, default: "medium"): Message priority (low, medium, high, urgent)
- `thread_id` (string, optional): Conversation thread ID

**Response:**
```json
{
  "success": true,
  "message_id": "msg-1691601740123-abc123def",
  "target_address": "bzzz://reviewer-001:reviewer@myproject:code_review",
  "message_type": "review_request",
  "delivery_results": {
    "delivered": true,
    "recipients": ["reviewer-001"],
    "delivery_time": 145
  },
  "posted_at": "2025-08-09T16:22:20Z"
}
```

### bzzz_thread

Manage threaded conversations between agents.

**Parameters:**
- `action` (string, required): Action to perform
  - `create`: Start new thread
  - `join`: Join existing thread
  - `leave`: Leave thread
  - `list`: List threads for agent
  - `summarize`: Generate thread summary
- `thread_id` (string, conditional): Required for join, leave, summarize actions
- `participants` (string[], conditional): Required for create action
- `topic` (string, conditional): Required for create action

**Create Thread Response:**
```json
{
  "success": true,
  "action": "create",
  "thread_id": "thread-1691601740123-xyz789",
  "result": {
    "id": "thread-1691601740123-xyz789",
    "topic": "API Design Review",
    "participants": ["architect-001", "reviewer-001"],
    "creator": "architect-001",
    "status": "active",
    "created_at": "2025-08-09T16:22:20Z"
  },
  "timestamp": "2025-08-09T16:22:20Z"
}
```

**List Threads Response:**
```json
{
  "success": true,
  "action": "list",
  "result": [
    {
      "id": "thread-1691601740123-xyz789",
      "topic": "API Design Review",
      "participants": ["architect-001", "reviewer-001"],
      "status": "active",
      "last_activity": "2025-08-09T16:20:15Z",
      "message_count": 5
    }
  ],
  "timestamp": "2025-08-09T16:22:20Z"
}
```

### bzzz_subscribe

Subscribe to real-time events from the BZZZ network.

**Parameters:**
- `event_types` (string[], required): Types of events to subscribe to
- `filter_address` (string, optional): Address pattern to filter events
- `callback_webhook` (string, optional): Webhook URL for notifications

**Event Types:**
- `agent_announcement`: Agent joins/leaves network
- `task_assignment`: Tasks assigned to agents
- `thread_created`: New conversation threads
- `thread_escalated`: Thread escalations
- `network_status`: Network status changes

**Response:**
```json
{
  "success": true,
  "subscription_id": "sub-1691601740123-def456",
  "event_types": ["agent_announcement", "task_assignment"],
  "filter_address": "bzzz://*:architect@*",
  "subscribed_at": "2025-08-09T16:22:20Z",
  "status": "active"
}
```

## Agent Management

### Agent Interface

```typescript
interface Agent {
  id: string;                    // Unique agent identifier
  role: string;                  // Agent role (architect, reviewer, etc.)
  capabilities: string[];        // List of capabilities
  specialization: string;        // Area of expertise
  maxTasks: number;             // Maximum concurrent tasks
  currentTasks: AgentTask[];    // Currently assigned tasks
  status: 'idle' | 'busy' | 'offline' | 'error';
  performance: number;          // Performance score (0-1)
  available: boolean;           // Availability status
  systemPrompt: string;         // GPT-5 system prompt
  createdAt: string;           // Creation timestamp
  lastActivity: string;        // Last activity timestamp
  metadata: Record<string, any>; // Additional metadata
}
```

### Task Interface

```typescript
interface AgentTask {
  id: string;                   // Unique task identifier
  type: string;                // Task type
  description: string;         // Task description
  status: 'pending' | 'in_progress' | 'completed' | 'failed';
  startTime: string;          // Task start time
  endTime?: string;           // Task completion time
  result?: any;               // Task result
  error?: string;             // Error message if failed
}
```

### Task Types

#### chat_completion
General purpose chat completion task.

**Task Data:**
```typescript
{
  messages: ChatMessage[];     // Conversation messages
  model?: string;             // Override default model
  temperature?: number;       // Override temperature
  maxTokens?: number;        // Override token limit
}
```

#### code_review
Code review and analysis task.

**Task Data:**
```typescript
{
  code: string;              // Code to review
  language: string;          // Programming language
  context?: string;          // Additional context
}
```

#### documentation
Documentation generation task.

**Task Data:**
```typescript
{
  content: string;           // Content to document
  documentType: string;      // Type of documentation
  audience: string;          // Target audience
}
```

#### architecture_analysis
System architecture analysis task.

**Task Data:**
```typescript
{
  systemDescription: string; // System to analyze
  requirements: string;      // System requirements
  constraints: string;       // System constraints
}
```

## Conversation Management

### Thread Interface

```typescript
interface ConversationThread {
  id: string;                    // Unique thread identifier
  topic: string;                 // Thread topic/subject
  participants: string[];        // Participant agent IDs
  creator: string;              // Thread creator ID
  status: 'active' | 'paused' | 'completed' | 'escalated';
  createdAt: string;           // Creation timestamp
  lastActivity: string;        // Last activity timestamp
  messages: ThreadMessage[];   // Thread messages
  metadata: Record<string, any>; // Thread metadata
  escalationHistory: EscalationEvent[]; // Escalation events
  summary?: string;            // Thread summary
}
```

### Message Interface

```typescript
interface ThreadMessage {
  id: string;                  // Unique message identifier
  threadId: string;           // Parent thread ID
  sender: string;             // Sender agent ID
  content: string;            // Message content
  messageType: 'text' | 'code' | 'file' | 'decision' | 'question';
  timestamp: string;          // Message timestamp
  replyTo?: string;           // Reply to message ID
  metadata: Record<string, any>; // Message metadata
}
```

### Escalation Events

```typescript
interface EscalationEvent {
  id: string;                 // Unique escalation ID
  threadId: string;          // Parent thread ID
  rule: string;              // Triggered escalation rule
  reason: string;            // Escalation reason
  triggeredAt: string;       // Escalation timestamp
  actions: EscalationAction[]; // Actions taken
  resolved: boolean;         // Resolution status
  resolution?: string;       // Resolution description
}
```

## P2P Connector

### Network Peer Interface

```typescript
interface NetworkPeer {
  id: string;                 // Peer identifier
  address: string;           // Network address
  capabilities: string[];    // Peer capabilities
  lastSeen: string;         // Last seen timestamp
  status: 'online' | 'offline' | 'busy';
}
```

### Subscription Interface

```typescript
interface BzzzSubscription {
  id: string;                // Subscription identifier
  eventTypes: string[];      // Subscribed event types
  filterAddress?: string;    // Address filter pattern
  callbackWebhook?: string;  // Callback webhook URL
  subscriberId: string;      // Subscriber agent ID
}
```

## OpenAI Integration

### Completion Options

```typescript
interface CompletionOptions {
  model?: string;            // Model to use (default: gpt-5)
  temperature?: number;      // Temperature (0-2, default: 0.7)
  maxTokens?: number;        // Max tokens (default: 4000)
  systemPrompt?: string;     // System prompt
  messages?: ChatMessage[];  // Conversation messages
}
```

### Completion Result

```typescript
interface CompletionResult {
  content: string;           // Generated content
  usage: TokenUsage;         // Token usage statistics
  model: string;            // Model used
  finishReason: string;     // Completion finish reason
  cost: number;             // Estimated cost (USD)
}
```

### Token Usage

```typescript
interface TokenUsage {
  promptTokens: number;      // Input tokens used
  completionTokens: number;  // Output tokens generated
  totalTokens: number;       // Total tokens consumed
}
```

## Cost Tracker

### Cost Usage Interface

```typescript
interface CostUsage {
  date: string;              // Date (YYYY-MM-DD or YYYY-MM)
  totalCost: number;         // Total cost in USD
  apiCalls: number;          // Number of API calls
  tokens: {
    prompt: number;          // Total prompt tokens
    completion: number;      // Total completion tokens
    total: number;          // Total tokens
  };
  models: Record<string, {
    calls: number;           // Calls per model
    cost: number;           // Cost per model
    tokens: number;         // Tokens per model
  }>;
}
```

### Cost Limits

```typescript
interface CostTrackerConfig {
  dailyLimit: number;        // Daily spending limit (USD)
  monthlyLimit: number;      // Monthly spending limit (USD)
  warningThreshold: number;  // Warning threshold (0-1)
}
```

### Cost Events

The cost tracker emits the following events:

- `warning`: Emitted when usage exceeds warning threshold
- `limit_exceeded`: Emitted when usage exceeds daily/monthly limits

## Configuration

### Main Configuration Interface

```typescript
interface BzzzMcpConfig {
  openai: {
    apiKey: string;          // OpenAI API key
    defaultModel: string;    // Default model (gpt-5)
    maxTokens: number;       // Default max tokens
    temperature: number;     // Default temperature
  };
  bzzz: {
    nodeUrl: string;         // BZZZ Go service URL
    networkId: string;       // Network identifier
    pubsubTopics: string[];  // PubSub topic subscriptions
  };
  cost: {
    dailyLimit: number;      // Daily cost limit
    monthlyLimit: number;    // Monthly cost limit
    warningThreshold: number; // Warning threshold
  };
  conversation: {
    maxActiveThreads: number; // Max concurrent threads
    defaultTimeout: number;   // Thread timeout (seconds)
    escalationRules: EscalationRule[]; // Escalation rules
  };
  agents: {
    maxAgents: number;       // Maximum agents
    defaultRoles: AgentRoleConfig[]; // Default role configs
  };
  logging: {
    level: string;           // Log level
    file?: string;           // Log file path
  };
}
```

### Escalation Rules

```typescript
interface EscalationRule {
  name: string;              // Rule name
  conditions: EscalationCondition[]; // Trigger conditions
  actions: EscalationAction[]; // Actions to take
  priority: number;          // Rule priority
}

interface EscalationCondition {
  type: 'thread_duration' | 'no_progress' | 'disagreement_count' | 'error_rate';
  threshold: number | boolean; // Condition threshold
  timeframe?: number;        // Time window (seconds)
}

interface EscalationAction {
  type: 'notify_human' | 'request_expert' | 'escalate_to_architect' | 'create_decision_thread';
  target?: string;           // Action target
  priority?: string;         // Action priority
  participants?: string[];   // Additional participants
}
```

## Error Handling

### Standard Error Response

```typescript
interface ErrorResponse {
  success: false;
  error: string;             // Error message
  code?: string;             // Error code
  details?: any;             // Additional error details
  timestamp: string;         // Error timestamp
}
```

### Common Error Codes

- `INVALID_PARAMETERS`: Invalid or missing parameters
- `AGENT_NOT_FOUND`: Referenced agent doesn't exist
- `THREAD_NOT_FOUND`: Referenced thread doesn't exist
- `NETWORK_ERROR`: P2P network communication failure
- `OPENAI_ERROR`: OpenAI API error
- `COST_LIMIT_EXCEEDED`: Cost limit exceeded
- `ESCALATION_FAILED`: Thread escalation failed

### Error Handling Best Practices

1. **Always check response.success** before processing results
2. **Log errors** with appropriate detail level
3. **Implement retry logic** for transient network errors
4. **Handle cost limit errors** gracefully with user notification
5. **Provide meaningful error messages** to users and logs

## Rate Limits and Throttling

### OpenAI API Limits
- **GPT-5**: Rate limits depend on your OpenAI tier
- **Tokens per minute**: Varies by subscription
- **Requests per minute**: Varies by subscription

### BZZZ Network Limits
- **Messages per second**: Configurable per node
- **Thread creation**: Limited by `maxActiveThreads`
- **Subscription limits**: Limited by network capacity

### Handling Rate Limits

1. **Implement exponential backoff** for retries
2. **Monitor usage patterns** and adjust accordingly
3. **Use streaming** for real-time applications
4. **Cache results** where appropriate
5. **Implement circuit breakers** for failing services

## Monitoring and Observability

### Health Check Endpoints

While the MCP server doesn't expose HTTP endpoints directly, you can monitor health through:

1. **Log analysis**: Monitor error rates and response times
2. **Cost tracking**: Monitor API usage and costs
3. **Agent performance**: Track task completion rates
4. **Thread metrics**: Monitor conversation health
5. **Network connectivity**: Monitor P2P connection status

### Metrics to Monitor

- **Agent availability**: Percentage of agents online and available
- **Task completion rate**: Successful task completion percentage
- **Average response time**: Time from task assignment to completion
- **Thread escalation rate**: Percentage of threads requiring escalation
- **Cost per interaction**: Average cost per agent interaction
- **Network latency**: P2P network communication delays

This completes the comprehensive API reference for the BZZZ MCP Server. Use this reference when integrating with the server or developing new features.