API ReferenceServer Package

Server Package

The @dexwox-labs/a2a-server package provides a complete server implementation for hosting A2A agents with HTTP/WebSocket support.

Overview

The server package includes the main server class and supporting components:

Installation

npm install @dexwox-labs/a2a-server
# or
npm install @dexwox-labs/a2a-node  # includes all packages

Quick Start

import { A2AServer, DefaultAgentExecutor } from '@dexwox-labs/a2a-server';
 
// Create an agent executor
const executor = new DefaultAgentExecutor({
  async executeTask(task) {
    // Your agent logic here
    return {
      status: 'completed',
      result: `Processed: ${task.name}`
    };
  }
});
 
// Create and start server
const server = new A2AServer({
  agentCard: {
    id: 'my-agent',
    name: 'My Agent',
    capabilities: ['text-processing'],
    endpoint: 'http://localhost:3000',
    version: '1.0.0'
  },
  executor
});
 
await server.start(3000);
console.log('🚀 A2A server running on http://localhost:3000');

Classes

A2AServer

A2AServer - Main server class that handles HTTP/WebSocket requests and manages the agent lifecycle.

Key methods:

  • start(port) - Start the server on specified port
  • stop() - Stop the server gracefully
  • use(middleware) - Add middleware to the server

Key features:

  • HTTP and WebSocket support
  • Built-in CORS handling
  • Request validation
  • Error handling middleware
  • Health check endpoints

TaskManager

TaskManager - Manages task lifecycle, state transitions, and persistence.

Key methods:

  • createTask(taskData) - Create a new task
  • updateTaskStatus(taskId, status) - Update task status
  • getTask(taskId) - Retrieve task by ID
  • cancelTask(taskId) - Cancel a running task

Key features:

  • Task state management
  • Status transition validation
  • Task history tracking
  • Cleanup and retention policies

DefaultAgentExecutor

DefaultAgentExecutor - Default implementation of the AgentExecutor interface.

Key methods:

  • executeTask(task) - Execute a task and return results
  • validateTask(task) - Validate task input
  • onTaskStart(task) - Hook called when task starts
  • onTaskComplete(task, result) - Hook called when task completes
  • onTaskError(task, error) - Hook called when task fails

DefaultRequestHandler

DefaultRequestHandler - Handles HTTP request processing and routing.

Key features:

  • Request routing
  • Input validation
  • Response formatting
  • Error handling
  • CORS support

Agent Implementation

To create a custom agent, implement the AgentExecutor interface:

import { AgentExecutor, Task, TaskResult } from '@dexwox-labs/a2a-server';
 
class MyAgentExecutor implements AgentExecutor {
  async executeTask(task: Task): Promise<TaskResult> {
    const { name, input } = task;
    
    switch (name) {
      case 'process-text':
        return this.processText(input);
      case 'analyze-data':
        return this.analyzeData(input);
      default:
        throw new Error(`Unknown task: ${name}`);
    }
  }
  
  private async processText(input: any): Promise<TaskResult> {
    // Your text processing logic
    return {
      status: 'completed',
      result: { processedText: input.text.toUpperCase() },
      artifacts: [{
        id: `text-${Date.now()}`,
        type: 'text',
        content: { text: input.text.toUpperCase() },
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }]
    };
  }
  
  private async analyzeData(input: any): Promise<TaskResult> {
    // Your data analysis logic
    return {
      status: 'completed',
      result: { analysis: 'Data analyzed successfully' }
    };
  }
}

Server Configuration

The A2AServer accepts comprehensive configuration options:

const server = new A2AServer({
  // Agent configuration
  agentCard: {
    id: 'advanced-agent',
    name: 'Advanced Agent',
    description: 'A sophisticated A2A agent',
    version: '2.0.0',
    capabilities: ['text-processing', 'data-analysis'],
    endpoint: 'https://agent.example.com'
  },
  
  // Executor
  executor: new MyAgentExecutor(),
  
  // Server options
  port: 3000,
  host: '0.0.0.0',
  
  // Task manager configuration
  taskManager: {
    maxConcurrentTasks: 10,
    taskTimeout: 300000, // 5 minutes
    cleanupInterval: 60000, // 1 minute
    retentionPeriod: 86400000 // 24 hours
  },
  
  // WebSocket configuration
  websocket: {
    enabled: true,
    path: '/ws',
    heartbeatInterval: 30000
  },
  
  // Security configuration
  security: {
    rateLimit: {
      windowMs: 60000, // 1 minute
      max: 100 // requests per window
    },
    authentication: {
      enabled: true,
      strategy: 'bearer',
      verify: async (token) => {
        // Your authentication logic
        return verifyToken(token);
      }
    }
  }
});

Middleware

Add custom middleware to extend server functionality:

// Logging middleware
server.use((req, res, next) => {
  console.log(`${req.method} ${req.path}`);
  next();
});
 
// Authentication middleware
server.use(async (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  if (!token) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  
  try {
    const user = await verifyToken(token);
    req.user = user;
    next();
  } catch (error) {
    return res.status(401).json({ error: 'Invalid token' });
  }
});
 
// Error handling middleware
server.use((error, req, res, next) => {
  console.error('Server error:', error);
  res.status(500).json({
    error: {
      code: 'INTERNAL_SERVER_ERROR',
      message: 'An unexpected error occurred'
    }
  });
});

WebSocket Support

Enable real-time communication with WebSocket support:

const server = new A2AServer({
  agentCard,
  executor,
  websocket: {
    enabled: true,
    path: '/ws',
    heartbeatInterval: 30000
  }
});
 
// Handle WebSocket connections
server.on('websocket:connection', (ws, req) => {
  console.log('New WebSocket connection');
  
  ws.on('message', async (data) => {
    const message = JSON.parse(data.toString());
    // Handle WebSocket messages
  });
  
  ws.on('close', () => {
    console.log('WebSocket connection closed');
  });
});

Health Monitoring

Built-in health check endpoints:

// Health check endpoint
// GET /health
{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00Z",
  "uptime": 3600,
  "memory": {
    "rss": 50331648,
    "heapTotal": 20971520,
    "heapUsed": 15728640
  },
  "tasks": {
    "active": 5,
    "completed": 150
  }
}
 
// Metrics endpoint  
// GET /metrics
{
  "requests_total": 1000,
  "tasks_created_total": 150,
  "tasks_completed_total": 145,
  "tasks_failed_total": 5,
  "response_time_seconds": {
    "avg": 0.25,
    "p95": 0.5,
    "p99": 1.0
  }
}

Error Handling

The server provides comprehensive error handling:

import { 
  A2AError, 
  TaskNotFoundError, 
  InvalidTaskStateError 
} from '@dexwox-labs/a2a-core';
 
// In your executor
class MyAgentExecutor implements AgentExecutor {
  async executeTask(task: Task): Promise<TaskResult> {
    try {
      // Validate input
      if (!task.input) {
        throw new A2AError('VALIDATION_ERROR', 'Task input is required');
      }
      
      // Process task
      const result = await this.processTask(task);
      return result;
      
    } catch (error) {
      if (error instanceof A2AError) {
        throw error; // Re-throw A2A errors
      } else {
        // Wrap other errors
        throw new A2AError('TASK_EXECUTION_FAILED', error.message);
      }
    }
  }
}

Production Deployment

For production deployment, consider these configurations:

const server = new A2AServer({
  agentCard,
  executor,
  
  // Production settings
  security: {
    rateLimit: {
      windowMs: 60000,
      max: 1000
    },
    authentication: {
      enabled: true,
      strategy: 'bearer'
    }
  },
  
  // Monitoring
  monitoring: {
    enabled: true,
    metricsPath: '/metrics',
    healthPath: '/health'
  },
  
  // Logging
  logging: {
    level: 'info',
    format: 'json'
  }
});

Next Steps