Skip to main content

Why Services?

Actions handle one-off tasks. But what about:
  • Persistent connections to Discord, Telegram, databases?
  • Background jobs like monitoring, cleanup, scheduling?
  • Shared resources like connection pools, caches?
Services fill this gap. They start with your agent and run continuously.
One instance per type. Services are singletons - getService('discord') always returns the same instance.

Available Service Types


Service System

Services are long-running background tasks that extend agent functionality beyond request-response patterns. They manage connections, handle events, and perform ongoing operations.

Service Interface

Abstract Service Class

Service Properties

  • serviceType: Unique identifier for the service type
  • capabilityDescription: Human-readable description of service capabilities
  • config: Optional configuration object
  • start: Static method to initialize and start the service
  • stop: Instance method to gracefully shut down the service

Service Types

Core Service Types

The core package defines base service types:

Plugin Service Types

Plugins extend service types through module augmentation:

Service Lifecycle

Lifecycle Phases

  1. Registration: Service registered with runtime during plugin initialization
  2. Queuing: Service queued for startup
  3. Initialization: Runtime prepares service environment
  4. Start: Service start() method called
  5. Running: Service actively processing
  6. Stop: Graceful shutdown initiated
  7. Cleanup: Resources released

Common Service Patterns

Platform Integration Service

Services that connect to external platforms:

Background Task Service

Services that perform periodic or scheduled tasks:

Data Service

Services that provide data access or caching:

Model Provider Service

Services that provide AI model access:

Service Registration

Plugin Registration

Services are registered during plugin initialization:

Manual Registration

Services can also be registered manually:

Service Management

Getting Services

Access services through the runtime:

Service Communication

Services can interact with each other:

Error Handling

Graceful Initialization

Handle missing configuration gracefully:

Error Recovery

Implement retry logic and error recovery:

Graceful Shutdown

Ensure proper cleanup on service stop:

Best Practices

Service Design

  • Single Responsibility: Each service should have one clear purpose
  • Stateless When Possible: Avoid maintaining state that could be lost
  • Idempotent Operations: Operations should be safe to retry
  • Resource Management: Clean up resources properly
  • Error Isolation: Errors shouldn’t crash other services

Configuration

  • Environment Variables: Use for sensitive configuration
  • Graceful Defaults: Provide sensible defaults
  • Validation: Validate configuration on startup
  • Hot Reload: Support configuration updates without restart

Performance

  • Async Operations: Use async/await for non-blocking operations
  • Connection Pooling: Reuse connections when possible
  • Caching: Cache frequently accessed data
  • Rate Limiting: Respect external API limits
  • Monitoring: Log performance metrics

Reliability

  • Health Checks: Implement health check endpoints
  • Circuit Breakers: Prevent cascade failures
  • Retry Logic: Handle transient failures
  • Graceful Degradation: Continue with reduced functionality
  • Audit Logging: Log important operations

Common Services

Model Context Protocol (MCP) Services

MCP (Model Context Protocol) allows your ElizaOS agent to use external tools and services. Think of it as giving your agent abilities like web search, file access, or API connections.

MCP Plugin Setup

Add MCP to your character’s plugins:

MCP Server Types

MCP supports two types of servers:

1. STDIO Servers

STDIO servers run as local processes and communicate through standard input/output.
Capabilities:
  • Search the web for current information
  • Extract content from websites
  • Perform deep research on topics
  • Scrape structured data

2. SSE Servers

SSE (Server-Sent Events) servers connect to remote APIs through HTTP.
Capabilities:
  • Real-time data access
  • API interactions
  • Custom tool execution
  • Dynamic resource fetching

Complete MCP Configuration Example

Testing MCP Integration

  1. Start your agent:
  1. Ask your agent to use the tools:
    • For web search: “Search for [topic]”
    • For API tools: Use commands specific to your SSE server

MCP Troubleshooting

  • Server not connecting: Check that the command/URL is correct
  • Tools not available: Ensure @elizaos/plugin-mcp is in your plugins array
  • Permission errors: For STDIO servers, ensure the command can be executed
  • CORS issues: For SSE servers, ensure proper CORS headers are configured

MCP Service Implementation

The MCP plugin internally creates services for each configured server:

Service Testing

Unit Testing

Test services in isolation:

Integration Testing

Test service interactions:

Task Worker System

Task workers enable background task execution with scheduling, validation, and lifecycle management. Tasks are persisted in the database while workers are registered in-memory.

Task Interface

TaskWorker Interface

Registering Task Workers

Creating Tasks

Task Execution Flow

Task Tags

Runtime Task Methods

Best Practices

  • Idempotent execution: Tasks may run multiple times on failures
  • Error handling: Catch errors in execute() to prevent task service crashes
  • Reasonable intervals: Don’t set updateInterval too low (< 1000ms)
  • Clean up: Delete completed one-time tasks to avoid database bloat
  • Validation: Use validate() to check preconditions before execution

See Also

Messaging

Build real-time messaging services

Sessions API

Manage stateful conversations

Events

Handle service lifecycle events

Models

Build model provider services