Skip to main content
The mofa db command provides database setup and migration tools for persistent storage backends.

Subcommands

init

Initialize database tables

schema

Show database schema SQL

mofa db init

Initialize persistence database tables for agents, sessions, and memory.

Usage

mofa db init -t <DB_TYPE> [OPTIONS]

Options

-t, --db-type <TYPE>

Required. Database type to initialize.
  • Type: Enum
  • Values: postgres, mysql, sqlite
mofa db init -t postgres

-o, --output <PATH>

Output SQL to file instead of stdout.
  • Type: Path
  • Default: Stdout
When specified, SQL is written to file instead of printed.
mofa db init -t postgres -o migration.sql

-u, --database-url <URL>

Database connection URL. When provided, executes SQL directly.
  • Type: String (connection URL)
  • Default: None (output only mode)
Direct database execution requires the db feature. Build with cargo install mofa-cli --features db.
mofa db init -t postgres \
  -u "postgresql://user:pass@localhost/mofa"

Examples

mofa db init -t postgres
Output:
-- MoFA PostgreSQL Schema
-- Copy and execute this SQL to initialize your database

CREATE TABLE IF NOT EXISTS agents (
    id VARCHAR(255) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    state VARCHAR(50) NOT NULL,
    started_at TIMESTAMP NOT NULL,
    provider VARCHAR(100),
    model VARCHAR(100),
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS sessions (
    session_id VARCHAR(255) PRIMARY KEY,
    agent_id VARCHAR(255),
    created_at TIMESTAMP NOT NULL,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    metadata JSONB,
    FOREIGN KEY (agent_id) REFERENCES agents(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS messages (
    id SERIAL PRIMARY KEY,
    session_id VARCHAR(255) NOT NULL,
    role VARCHAR(50) NOT NULL,
    content TEXT NOT NULL,
    timestamp TIMESTAMP NOT NULL,
    FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
);

CREATE INDEX idx_sessions_agent ON sessions(agent_id);
CREATE INDEX idx_messages_session ON messages(session_id);
CREATE INDEX idx_messages_timestamp ON messages(timestamp);

Save SQL to file

mofa db init -t postgres -o migration.sql
Output:
→ Generating postgres migration script...
✓ Migration script saved to: migration.sql
You can then execute the SQL manually:
psql -U user -d mofa -f migration.sql

Execute directly

mofa db init -t postgres \
  -u "postgresql://user:pass@localhost/mofa"
Output:
→ Initializing postgres database...
  URL: postgresql://user:****@localhost/mofa
  ✓ Created table: agents
  ✓ Created table: sessions
  ✓ Created table: messages
  ✓ Created indexes
✓ Database tables initialized successfully!

Database Types

PostgreSQL

mofa db init -t postgres -u "postgresql://user:pass@localhost/mofa"
Features:
  • JSONB support for metadata
  • Full-text search capabilities
  • Robust transaction support
  • Recommended for production

MySQL

mofa db init -t mysql -u "mysql://user:pass@localhost/mofa"
Features:
  • JSON column type
  • Wide hosting support
  • Good performance
  • Compatible with MariaDB

SQLite

mofa db init -t sqlite -u "sqlite://./mofa.db"
Features:
  • No server required
  • File-based storage
  • Great for development
  • Single-user scenarios

mofa db schema

Display the database schema SQL for a specific database type.

Usage

mofa db schema -t <DB_TYPE>

Options

-t, --db-type <TYPE>

Required. Database type to show schema for.
  • Type: Enum
  • Values: postgres, mysql, sqlite
mofa db schema -t postgres

Examples

PostgreSQL Schema

mofa db schema -t postgres
Output:
-- MoFA POSTGRES Schema
-- Copy and execute this SQL to initialize your database

CREATE TABLE IF NOT EXISTS agents (
    id VARCHAR(255) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    state VARCHAR(50) NOT NULL,
    started_at TIMESTAMP NOT NULL,
    provider VARCHAR(100),
    model VARCHAR(100),
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Additional tables and indexes...

MySQL Schema

mofa db schema -t mysql
Output:
-- MoFA MYSQL Schema
-- Copy and execute this SQL to initialize your database

CREATE TABLE IF NOT EXISTS agents (
    id VARCHAR(255) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    state VARCHAR(50) NOT NULL,
    started_at TIMESTAMP NOT NULL,
    provider VARCHAR(100),
    model VARCHAR(100),
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Additional tables and indexes...

SQLite Schema

mofa db schema -t sqlite
Output:
-- MoFA SQLITE Schema
-- Copy and execute this SQL to initialize your database

CREATE TABLE IF NOT EXISTS agents (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    state TEXT NOT NULL,
    started_at TEXT NOT NULL,
    provider TEXT,
    model TEXT,
    description TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP,
    updated_at TEXT DEFAULT CURRENT_TIMESTAMP
);

-- Additional tables and indexes...

Database Schema

Tables

agents

Stores agent metadata and state.
ColumnTypeDescription
idVARCHAR(255)Agent unique identifier (PK)
nameVARCHAR(255)Agent display name
stateVARCHAR(50)Current state (Running, Stopped, etc.)
started_atTIMESTAMPAgent start time
providerVARCHAR(100)LLM provider (optional)
modelVARCHAR(100)Model name (optional)
descriptionTEXTAgent description (optional)
created_atTIMESTAMPRecord creation time
updated_atTIMESTAMPRecord last update time

sessions

Stores conversation sessions.
ColumnTypeDescription
session_idVARCHAR(255)Session unique identifier (PK)
agent_idVARCHAR(255)Associated agent ID (FK)
created_atTIMESTAMPSession start time
updated_atTIMESTAMPSession last activity
metadataJSONB/JSON/TEXTCustom metadata

messages

Stores conversation messages.
ColumnTypeDescription
idSERIAL/INTMessage unique identifier (PK)
session_idVARCHAR(255)Associated session ID (FK)
roleVARCHAR(50)Message role (user, assistant, system, tool)
contentTEXTMessage content
timestampTIMESTAMPMessage timestamp

Indexes

-- Session lookups by agent
CREATE INDEX idx_sessions_agent ON sessions(agent_id);

-- Message lookups by session
CREATE INDEX idx_messages_session ON messages(session_id);

-- Time-based message queries
CREATE INDEX idx_messages_timestamp ON messages(timestamp);

Connection URLs

PostgreSQL

# Basic format
postgresql://user:password@host:port/database

# Example
postgresql://mofa_user:secret@localhost:5432/mofa

# With SSL
postgresql://user:pass@host/db?sslmode=require

# Unix socket
postgresql:///dbname?host=/var/run/postgresql

MySQL

# Basic format
mysql://user:password@host:port/database

# Example
mysql://mofa_user:secret@localhost:3306/mofa

# With SSL
mysql://user:pass@host/db?ssl-mode=REQUIRED

# Unix socket
mysql://user:pass@localhost/db?socket=/var/run/mysqld/mysqld.sock

SQLite

# File path
sqlite://./mofa.db
sqlite:///absolute/path/to/mofa.db

# In-memory (testing only)
sqlite::memory:

Common Workflows

Initial Database Setup

# 1. Create database
creatdb mofa

# 2. Generate migration script
mofa db init -t postgres -o migration.sql

# 3. Review and execute
cat migration.sql
psql -d mofa -f migration.sql

# Or initialize directly
mofa db init -t postgres -u "postgresql://user:pass@localhost/mofa"

Configure Agent for Database

Edit agent.yml:
agent:
  id: my-agent
  name: My Agent

# Database configuration
persistence:
  enabled: true
  
  # PostgreSQL
  database:
    type: postgres
    url: ${DATABASE_URL}
  
  # Or SQLite
  # database:
  #   type: sqlite
  #   path: ~/.local/share/mofa/mofa.db

# Session persistence
session:
  persist: true
  ttl_seconds: 86400  # 24 hours
Set environment variable:
export DATABASE_URL="postgresql://user:pass@localhost/mofa"

Verify Database Setup

# Connect to database
psql -d mofa

# List tables
\dt

# Check schema
\d agents
\d sessions
\d messages

# Test query
SELECT * FROM agents LIMIT 1;

Backup Database

# Backup
pg_dump mofa > mofa_backup.sql

# Restore
psql mofa < mofa_backup.sql

Feature Flag

Direct database execution requires the db feature flag.
To enable database features:
# Install with database support
cargo install mofa-cli --features db

# Or build from source
cargo build --release --features db -p mofa-cli
Without the db feature, you can still:
  • Generate SQL migration scripts
  • Save scripts to files
  • Execute scripts manually

Security

Connection String Security

Never commit database URLs with credentials to version control.
Best practices:
  1. Use environment variables:
export DATABASE_URL="postgresql://user:pass@localhost/mofa"
mofa db init -t postgres -u "$DATABASE_URL"
  1. Use .env files (not committed):
# .env (add to .gitignore)
DATABASE_URL=postgresql://user:pass@localhost/mofa
  1. Use secrets management:
# AWS Secrets Manager
DATABASE_URL=$(aws secretsmanager get-secret-value \
  --secret-id mofa/db --query SecretString --output text)

Database User Permissions

Create a dedicated database user with minimal permissions:
-- PostgreSQL
CREATE USER mofa_app WITH PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE mofa TO mofa_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO mofa_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO mofa_app;

-- MySQL
CREATE USER 'mofa_app'@'localhost' IDENTIFIED BY 'secure_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON mofa.* TO 'mofa_app'@'localhost';
FLUSH PRIVILEGES;

Troubleshooting

Connection failed

mofa db init -t postgres -u "postgresql://localhost/mofa"
# Error: Failed to connect to PostgreSQL: ...
Solutions:
  • Check database is running: pg_isready
  • Verify connection details
  • Check firewall/network settings
  • Ensure database exists: createdb mofa

Permission denied

mofa db init -t postgres -u "postgresql://user:pass@localhost/mofa"
# Error: SQL error: permission denied for table agents
Solution: Grant required permissions to user.

Feature not available

mofa db init -t postgres -u "postgresql://localhost/mofa"
# Error: Direct database execution requires the 'db' feature
Solution: Install with database support:
cargo install mofa-cli --features db

See Also

Build docs developers (and LLMs) love