mhost Documentation
Everything you need to deploy, monitor, and scale processes in production.
Installation
Edit on GitHub ✎mhost ships as a single static binary with zero runtime dependencies. Pick your preferred method:
Homebrew (macOS / Linux)
curl installer (Linux / macOS)
Cargo (from source)
GitHub Releases (manual binary)
Docker
Nix
mhost --version. The daemon starts automatically on first use.
Quick Start
Edit on GitHub ✎Get your first process running in under 30 seconds.
Your First mhost.toml
Edit on GitHub ✎Create mhost.toml in your project root, then run mhost start — mhost will auto-discover the file.
How mhost Works
Edit on GitHub ✎mhost has two components: a persistent daemon and a CLI. The daemon spawns and supervises processes, stores logs in an embedded SQLite database, and exposes a JSON-RPC socket. The CLI communicates with the daemon over a Unix socket at ~/.mhost/mhost.sock.
The daemon starts automatically the first time you run any mhost command. To start it explicitly: mhost daemon start. To stop: mhost daemon stop.
Process Lifecycle
Edit on GitHub ✎Every process moves through these states:
| State | Description |
|---|---|
| stopped | Not running. Intentionally stopped or never started. |
| starting | Daemon is spawning the process. Health probes not yet checked. |
| online | Running and passing all health probes. |
| stopping | SIGTERM sent; waiting for graceful shutdown within grace period. |
| errored | Exited with non-zero code or failed health probe. Will auto-restart. |
State Directory (~/.mhost/)
Edit on GitHub ✎MHOST_HOME.
Starting Processes
Edit on GitHub ✎- --name <name>Assign a name (default: filename without extension).
- --instances <N>Number of instances to spawn (cluster mode).
- --max-memory <MB>Auto-restart when RSS exceeds this limit.
- --env <KEY=VAL>Inject environment variables (repeatable).
- --env-file <path>Load variables from a .env file.
- --cwd <path>Working directory for the process.
- --interpreter <bin>Override the auto-detected interpreter.
- --grace-period <dur>Time to wait for graceful shutdown (default: 10s).
- --no-autorestartDisable automatic restart on crash.
- --watchWatch files and restart on change (dev mode).
Auto-detect Interpreter
mhost infers the interpreter from the file extension so you can pass a filename directly:
| Extension | Interpreter | Override flag |
|---|---|---|
| .js / .mjs / .cjs | node | --interpreter bun |
| .ts | ts-node | --interpreter deno |
| .py | python3 | --interpreter pypy3 |
| .rb | ruby | – |
| .sh / .bash | bash | – |
| .php | php | – |
| (binary) | direct exec | – |
Stop, Restart, Delete
Zero-Downtime Reload
Send SIGUSR2 to trigger a rolling restart with no dropped requests. mhost brings up new instances before tearing down the old ones:
SIGUSR2 and finish in-flight requests before exiting. Most Node.js frameworks support this out of the box.
Index-based Process Targeting
Every process in the registry has a numeric index (shown in mhost list). You can use the index instead of the name in any command:
Scaling
Scale a named process to N instances at runtime with no downtime — mhost adds or removes workers gracefully:
Process Groups & Dependencies
Groups let you start, stop, and restart related processes together. Declare them in your config:
Save & Resurrect
Persist the current process list to disk so mhost can restore it after a system reboot:
mhost.toml Format
Edit on GitHub ✎Full configuration reference for a single process:
| Key | Type | Default | Description |
|---|---|---|---|
| command | string | required | Shell command or path to script. |
| instances | integer | 1 | Parallel worker count. |
| max_memory | string | – | e.g. "512MB", "2GB". Auto-restart on breach. |
| max_restarts | integer | 0 | Maximum restart attempts before marking errored. |
| grace_period | duration | "10s" | Graceful shutdown window before SIGKILL. |
| autorestart | bool | true | Restart on non-zero exit. |
| cron_restart | string | – | Cron expression for scheduled restarts. |
| watch | bool / [string] | false | true = watch all source files, or list of globs. |
YAML & JSON Alternatives
mhost auto-detects format by file extension. Use --config to specify a path:
All three formats support the same keys. TOML is recommended for production due to its comment support.
Environment Variable Expansion
Any string value in config can reference environment variables using ${VAR} syntax. Variables are resolved at daemon startup:
${VAR:-default} to supply fallbacks.
Health Probes
Three probe types are supported. A process is considered errored when the probe fails retries times consecutively.
HTTP Probe
TCP Probe
Script Probe
Cron Restarts
Schedule automatic restarts using standard cron syntax (UTC by default):
Memory Limits
When a process exceeds max_memory, mhost restarts it and fires a notification on configured channels. Supported suffixes: MB, GB.
Logs
Edit on GitHub ✎Live Streaming
Log Format
Each line is timestamped and prefixed with the process name and instance ID:
JSON lines are automatically pretty-printed in the terminal. Pass --raw to disable pretty-printing.
FTS5 Search
mhost stores all logs in SQLite with FTS5 full-text search. Query logs without grep:
External Log Sinks
Ship logs to external systems by configuring sinks in mhost.toml:
TUI Dashboard
Edit on GitHub ✎Opens a real-time terminal UI showing CPU, memory, restart count, uptime, and log tail for every process. Use arrow keys to navigate, r to restart, s to stop, q to quit.
Web Dashboard
Configure port and basic auth in ~/.mhost/config.toml:
Health Checks
View current health status at a glance:
Metrics & Prometheus
mhost exposes a Prometheus-compatible /metrics endpoint. Enable it in ~/.mhost/config.toml:
Exported metrics include: mhost_process_cpu_percent, mhost_process_memory_bytes, mhost_process_restarts_total, mhost_process_status, mhost_health_probe_duration_ms.
Notification Setup
Edit on GitHub ✎Run the interactive wizard to configure any channel:
All Channels
Telegram Example
Slack Example
Event Types
| Event | Description |
|---|---|
| crash | Process exited unexpectedly. |
| errored | Process entered errored state. |
| health_fail | Health probe failed. |
| health_recover | Health probe recovered. |
| memory_exceeded | RSS exceeded max_memory limit. |
| restart | Process was restarted (manual or auto). |
| deploy_start | Deployment started. |
| deploy_done | Deployment completed. |
| deploy_failed | Deployment failed. |
| brain_heal | Brain applied an auto-remediation. |
Throttling & Escalation
Prevent alert storms with per-channel throttling and escalation policies:
AI Setup
Edit on GitHub ✎AI Commands
| Command | Description |
|---|---|
mhost ai diagnose <app> | Analyze recent crashes and suggest root cause. |
mhost ai explain <app> | Explain what a process does based on its logs and command. |
mhost ai fix <app> | Suggest configuration fixes for an errored process. |
mhost ai logs <app> | Summarize recent log activity in plain English. |
mhost ai predict | Predict which processes are likely to fail in the next hour. |
mhost ai optimize <app> | Suggest memory and concurrency optimizations. |
mhost ai anomaly | Detect anomalous behaviour across all processes. |
mhost ai compare <app> <before> <after> | Compare log patterns before/after a deploy. |
mhost ai report | Generate a daily ops report for all processes. |
mhost ai ask "<question>" | Free-form question about your running stack. |
Prompt Customization
Override any built-in system prompt by placing a file in ~/.mhost/prompts/:
Autonomous Agent Setup
Edit on GitHub ✎Observe → Think → Act Loop
The agent runs a continuous loop every poll_interval:
Autonomy Levels
| Level | Behaviour |
|---|---|
supervised | Always asks for approval via Telegram before acting. |
semi | Acts autonomously for low-risk actions (restart); asks for high-risk ones (rollback, scale-up). |
autonomous | Full autonomy within configured bounds. Reports actions after the fact. |
Telegram Conversation Examples
You can also chat with the agent directly: mhost agent ask "why is worker slow today?"
Self-Healing Brain
Edit on GitHub ✎Built-in Playbooks
| Playbook | Trigger | Action |
|---|---|---|
| oom-restart | RSS > max_memory | Restart process, log incident. |
| rapid-crash | >3 crashes in 5 min | Stop, notify, wait for manual intervention. |
| health-recover | Probe fails 3x, then passes | Clear error state, update health score. |
| cpu-spike | CPU > 90% for 60s | Scale out by +1 instance. |
| zombie-process | PID alive, health probe dead 5min | SIGKILL, restart. |
| deploy-rollback | Error rate > 10% post-deploy | Auto-rollback to previous revision. |
Add custom playbooks in ~/.mhost/brain/playbooks/my-playbook.toml.
Health Scores
Each process gets a rolling health score (0–100) computed from crash frequency, probe success rate, memory trend, and CPU stability. Scores below 40 trigger notifications; below 20 trigger the brain.
Auto-Learning
When the brain successfully remediates a novel incident, it serializes the diagnosis → action → outcome chain into a new playbook. On the next identical incident the playbook runs locally — no AI API call needed, zero latency, zero cost.
Dev Mode
Edit on GitHub ✎File Watching
In dev mode, mhost watches files using OS-native events (inotify on Linux, FSEvents on macOS). Configure per-process watch paths in mhost.toml:
Env File Loading
mhost merges env files in this priority order (later overrides earlier):
Cloud Fleet Commands
Edit on GitHub ✎SSH Configuration
mhost uses your existing ~/.ssh/config by default. The key_file field is optional if the SSH agent is running.
Cloud Providers
| Provider | Import command | Auth |
|---|---|---|
| AWS EC2 | mhost cloud import aws | AWS_ACCESS_KEY_ID / IAM role |
| Azure VMs | mhost cloud import azure | AZURE_SUBSCRIPTION_ID + az login |
| DigitalOcean | mhost cloud import digitalocean | DIGITALOCEAN_TOKEN |
| Railway | mhost cloud import railway | RAILWAY_TOKEN |
AI Cloud Operations
Cloud-Native Providers
Direct API integration with 10 cloud providers — no SSH required. Provision, deploy, scale, and manage services via provider APIs.
| Provider | Services | Auth Command |
|---|---|---|
| AWS | ECS, EKS, EC2, Lambda | mhost cloud auth aws |
| GCP | Cloud Run, GKE, GCE | mhost cloud auth gcp |
| Azure | AKS, ACI, VMs | mhost cloud auth azure |
| Railway | Web, Worker, Cron | mhost cloud auth railway |
| Fly.io | Machines, Apps | mhost cloud auth fly |
| Vercel | Serverless, Edge | mhost cloud auth vercel |
| DigitalOcean | App Platform, Droplets | mhost cloud auth digitalocean |
| Cloudflare | Workers, Pages | mhost cloud auth cloudflare |
| Netlify | Sites, Functions | mhost cloud auth netlify |
| Supabase | Database, Edge Functions | mhost cloud auth supabase |
Cloud Secrets Management
Manage environment variables and secrets on cloud services without logging into provider dashboards.
Cloud Cost Tracking
Unified cost view across all configured cloud providers. See spending per service and per provider.
Configuration Drift Detection
Compare your local desired state against live cloud configuration. Optionally auto-fix detected drift.
Infrastructure Export
Export your cloud services as infrastructure-as-code for version control, migration, or disaster recovery.
| Format | Command | Output |
|---|---|---|
| Terraform | mhost cloud export terraform | .tf files |
| Docker Compose | mhost cloud export docker-compose | docker-compose.yml |
| Kubernetes | mhost cloud export kubernetes | Deployment + Service YAML |
Chat Bot Setup
Edit on GitHub ✎Chat Commands
| Command | Description |
|---|---|
| /status | List all processes and their states. |
| /status <app> | Detailed status for a single process. |
| /restart <app> | Restart a process. |
| /stop <app> | Stop a process. |
| /scale <app> <N> | Scale to N instances. |
| /logs <app> | Last 20 log lines. |
| /health | Health probe summary. |
| /deploy <app> | Trigger a deployment. |
| /rollback <app> | Rollback to previous revision. |
| /ask <question> | Ask the AI agent anything. |
Permission System
| Role | Allowed actions |
|---|---|
| admin | All commands including stop, delete, deploy, rollback, scale. |
| operator | restart, logs, status, health, scale. |
| viewer | status, logs, health (read-only). |
Deploy & Rollback
Edit on GitHub ✎Deploy Config
Hook Execution
All hooks run in the deploy path. A non-zero exit aborts the deployment and triggers rollback.
Reverse Proxy Config
Edit on GitHub ✎Load Balancing Strategies
| Strategy | Description |
|---|---|
| round-robin | Distribute requests evenly across all upstreams. |
| least-conn | Route to the upstream with fewest active connections. |
| ip-hash | Consistent routing based on client IP. |
| random | Random selection. |
| weighted | Weighted distribution (set weight per upstream). |
TLS / ACME
mhost integrates with Let's Encrypt via the ACME protocol. Set tls = true and provide a domain — certificates are auto-provisioned and renewed.
Zero-Downtime Reload
Start new instances, wait for health checks to pass, then kill old ones. No dropped requests.
mhost reload api-serverIf no health check is configured, falls back to a regular restart. If the new instances fail health checks, they are killed and the old instances are preserved.
Load Testing
Built-in HTTP load testing with configurable concurrency and duration.
# Default: 10 seconds, 10 concurrent workers
mhost bench https://api.example.com
# Custom settings
mhost bench https://api.example.com --duration 30 --concurrency 50Reports total requests, requests/second, average and p99 latency, and error rate.
Canary Deployments
Scale up a canary instance, monitor for errors over a duration, then auto-promote or rollback.
# Default: 10% traffic, 300s monitoring window
mhost canary api-server
# Custom canary settings
mhost canary api-server --percent 20 --duration 600Snapshots
Capture and restore full process state. Perfect for safe rollbacks before risky changes.
mhost snapshot create before-deploy # Save current state
mhost snapshot list # List all snapshots
mhost snapshot restore before-deploy # Restore a snapshotSSL Certificate Monitoring
Check SSL certificate expiry for one or more URLs. Warns when certificates expire within 30 days.
mhost certs --url https://api.example.com --url https://app.example.comSLA Uptime Reports
Calculate uptime from brain incident data, compare against your SLA target.
mhost sla api-server # Default target: 99.9%
mhost sla api-server --target 99.99 # Four-nines targetShows uptime percentage, allowed vs actual downtime, incidents count, and budget remaining.
Incident Replay
Replay an incident timeline for a process, showing events, log lines, and health score changes.
mhost replay api-server # Full timeline
mhost replay api-server --time "3:47am" # Filter around a timeProcess Dependency Graph
Visualize the dependency tree between your processes based on group configuration.
mhost linkCloud Cost Estimation
Maps running process memory usage to EC2-equivalent instance types and estimates monthly costs.
mhost costEnvironment Diff
Compare two fleet environments or server configs side-by-side.
mhost diff staging productionRecipe Runner
Execute a sequence of mhost commands from a text file. One command per line.
mhost run deploy-recipe.txtPM2 Migration
Auto-convert PM2 configuration to mhost format.
mhost migrate --from pm2 # Reads ~/.pm2/dump.pm2 → generates mhost.tomlREST API
mhost exposes 25 REST endpoints on port 19516 with JSON request/response format.
# Start the API server
mhost api start --port 19516
# List processes
curl -H "Authorization: Bearer mhost_tok_..." http://localhost:19516/api/v1/processes
# Start a new process
curl -X POST -H "Authorization: Bearer mhost_tok_..." \
-H "Content-Type: application/json" \
-d '{"script": "server.js", "name": "api"}' \
http://localhost:19516/api/v1/processes| Category | Endpoints | Auth |
|---|---|---|
| Processes | GET/POST/DELETE /processes/* | viewer/operator |
| Logs | GET /logs/:name, /logs/:name/search | viewer |
| Health | GET /health, /health/:name | public/viewer |
| Metrics | GET /metrics, /metrics/:name | viewer |
| System | POST /save, /resurrect, /kill | operator/admin |
| Tokens | GET/POST/DELETE /tokens/* | admin |
| Webhooks | GET/POST/DELETE /webhooks/* | admin |
Authentication
Bearer token authentication with role-based access control. Tokens are hashed with Argon2 before storage.
# Create a token with a specific role
mhost api token create --name my-app --role operator
# List active tokens
mhost api token list
# Revoke a token
mhost api token revoke <id>Four roles with increasing permissions: viewer (read-only), operator (start/stop/restart), admin (token and webhook management), super_admin (full access).
WebSocket Streaming
Real-time event, log, and metrics streaming over WebSocket at /api/v1/ws.
# Connect with token
wscat -c "ws://localhost:19516/api/v1/ws?token=mhost_tok_..."
# Subscribe to channels
{"type": "subscribe", "channel": "events"}
{"type": "subscribe", "channel": "logs", "process": "api-server"}
{"type": "subscribe", "channel": "metrics"}
# Unsubscribe
{"type": "unsubscribe", "channel": "events"}Channels: events (process lifecycle), logs (stdout/stderr per process), metrics (CPU/memory snapshots).
Outbound Webhooks
Register HTTP endpoints to receive process events. Payloads are signed with HMAC-SHA256.
# Register a webhook
mhost api webhook add --url https://myapp.com/hook --events crash,restart --secret my-key
# List registered webhooks
mhost api webhook list
# Test a webhook
mhost api webhook test <id>
# View failed deliveries
mhost api webhook failuresFeatures: configurable retry with exponential backoff, dead letter logging for failed deliveries, per-webhook secret for payload verification.
CLI Reference
Edit on GitHub ✎| Command | Description |
|---|---|
mhost start <app> | Start a process or config file. |
mhost stop <app|all> | Gracefully stop. |
mhost restart <app|all> | Restart. |
mhost reload <app> | Zero-downtime reload. |
mhost delete <app> | Stop and remove from registry. |
mhost status [app] | Process status table. |
mhost logs [app] | Show logs. |
mhost monit | TUI dashboard. |
mhost dashboard | Web UI. |
mhost scale <app> <N> | Scale to N instances. |
mhost save | Persist process list. |
mhost resurrect | Restore from snapshot. |
mhost startup | Install system init script. |
mhost deploy | Run deployment. |
mhost rollback | Rollback deployment. |
mhost health | Health probe summary. |
mhost notify setup | Configure notifications. |
mhost ai <cmd> | AI commands. |
mhost agent <cmd> | Autonomous agent. |
mhost brain <cmd> | Self-healing brain. |
mhost bot <cmd> | Chat bot control. |
mhost cloud <cmd> | Cloud fleet management. |
mhost dev | Dev mode with file watching. |
mhost bench <url> | HTTP load testing. |
mhost canary <app> | Canary deployment. |
mhost snapshot create|list|restore | State snapshots. |
mhost replay <process> | Incident timeline replay. |
mhost link | Dependency graph. |
mhost cost | Cloud cost estimation. |
mhost certs [--url] | SSL certificate monitoring. |
mhost sla <app> | SLA uptime report. |
mhost diff <a> <b> | Environment comparison. |
mhost share <app> | Tunnel exposure. |
mhost run <file> | Recipe runner. |
mhost migrate --from <pm> | PM2 migration. |
mhost playground | Interactive tutorial. |
mhost api start [--port] | Start API server. |
mhost api stop | Stop API server. |
mhost api status | API server status. |
mhost api token create|list|revoke | Token management. |
mhost api webhook add|list|remove|test|failures | Webhook management. |
mhost daemon start|stop|status | Daemon lifecycle. |
Exit Codes
| Code | Meaning |
|---|---|
| 0 | Success. |
| 1 | General error. |
| 2 | Configuration error. |
| 3 | Process not found. |
| 4 | Daemon not running. |
| 5 | IPC communication error. |
| 6 | Deployment failed. |
API Reference
Edit on GitHub ✎The daemon exposes a JSON-RPC 2.0 API over a Unix socket at ~/.mhost/mhost.sock. You can also enable an HTTP JSON-RPC endpoint.
Socket Location
Example Request
RPC Methods
| Method | Description |
|---|---|
| process.list | List all processes. |
| process.status | Get status for one process. |
| process.start | Start a process. |
| process.stop | Stop a process. |
| process.restart | Restart a process. |
| process.delete | Delete a process. |
| process.scale | Scale a process. |
| logs.query | Query logs with filters. |
| logs.stream | Subscribe to live log stream (WebSocket). |
| health.status | Get health probe results. |
| metrics.snapshot | Get current CPU/memory metrics. |
| deploy.trigger | Trigger a deployment. |
| deploy.rollback | Roll back to a previous revision. |
| brain.status | Get brain health scores. |
| daemon.version | Get daemon version info. |
[rpc] http = true in ~/.mhost/config.toml. The socket endpoint is always active when the daemon is running.