universal-agent-recovery
This MCP server lets an agent register and manage recoverable coding tasks while a watchdog monitors and resumes them after interruptions.
Register tasks with task/session/process metadata and working directory.
Send progress heartbeats and save verified checkpoints with structured details.
Report errors/interruptions so recovery can be scheduled.
Query full task status, recovery attempts, checkpoint, and recent events.
Mark tasks completed only with a verification note.
Cancel tasks and stop further recovery attempts.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@universal-agent-recovery register this task so it auto-resumes if my session crashes"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Universal Agent Recovery
Your coding agent crashed at 80% of the task. Who restarts it? This package does.
universal-agent-recovery is an MCP server + independent watchdog (npm package: s-universal-agent-recovery) that automatically detects when a coding agent task is interrupted (crash, timeout, lost session) and resumes it — from the same session when possible, or from a saved checkpoint otherwise.
Agent doing work ── crash ──> watchdog detects ──> resumes from checkpoint
│
┌───────────────────┘
▼
recovered → agent continues the taskComponent | CLI | Role |
MCP Server |
| Tools for the agent to register tasks, report progress, save checkpoints |
Watchdog |
| Independent process that detects interruptions and launches recovery |
State dump |
| Read-only JSON snapshot of tasks/leases/retries for debugging |
Works with OpenCode, Claude Code, and any agent via a generic CLI template adapter.
No native dependencies — uses Node's built-in SQLite (
node >= 22.5, 22.x only).The watchdog never depends on the agent being alive to perform recovery.
Node version: this package targets Node.js 22.x (
>=22.5.0 <23) because storage uses the built-innode:sqlitemodule, whose behavior can change between major lines. Node 23+/24+ may work but is untested; the(node:xxx) ExperimentalWarning: SQLite is an experimental featuremessage at startup is expected and harmless.
Quick start
npm install -g s-universal-agent-recovery1. Register the MCP server in your MCP client
OpenCode — add to ~/.config/opencode/opencode.json (or project opencode.json):
{
"mcp": {
"universal-agent-recovery": {
"type": "local",
"command": ["uar-mcp"],
"enabled": true
}
}
}Claude Code:
claude mcp add universal-agent-recovery -- uar-mcpAny other MCP client — command uar-mcp, transport stdio.
2. Start the watchdog in the background
uar-watchdogThat's it. From now on, whenever the agent calls register_task at the start of significant work, the task is monitored and auto-resumed on interruption.
3. Optional: try the demo
npm run demo # scripted end-to-end recovery with a mock agentRelated MCP server: Aletheia Token Guard (ATG)
How it works
The agent (via MCP tools) records what it is doing; the watchdog watches the record and recovers when the record goes stale.
┌─────────────────────────┐
│ SQLite state store │
│ (shared, WAL mode) │
└──────────┬──────────────┘
register/heartbeat │ poll + claim
┌────────────────────────┴──────────────────────┐
│ │
MCP Server (uar-mcp) Watchdog (uar-watchdog)
- register_task - detects stale heartbeat / dead pid
- report_progress / save_checkpoint - verifies the session still exists
- report_interruption - resumes: same session → checkpoint fallback
- mark_completed / cancel_task - retry budget + backoff + single-owner lockRecovery lifecycle
Register — agent calls
register_task(session id, adapter, working directory).Progress — agent calls
report_progress/save_checkpointas work proceeds.Detect — watchdog sees a stale heartbeat (and/or dead pid) → task is
INTERRUPTED.Verify — watchdog checks the session still exists (adapters that support it).
Resume — watchdog launches the agent with the same session id + a self-contained recovery instruction.
Fallback — resume failed? A fresh session is started from the persisted checkpoint.
Verify — recovery succeeded only when the agent resumes making progress or reports completion.
Repeat — until
COMPLETED,BLOCKED(retry budget exhausted), orCANCELLED.
Interruption scenarios → when recovery triggers
Scenario | Detected by | Resumed? |
Network loss → agent CLI crashes → process dies |
| ✅ ≤ ~30s (next poll) |
Network loss → CLI hangs, process alive, no pid known | stale heartbeat ( | ✅ after 10 min (default) |
Agent retries internally, then exits | dead pid | ✅ ≤ ~30s |
Agent retries internally, then goes silent with process still alive | heartbeat stale but pid alive | ❌ classified |
Agent reports | tool call | ✅ immediately (next poll) |
Design note: a live process with a stale heartbeat is deliberately classified as
IDLE, notINTERRUPTED. From the outside, "running a 15-minute test suite", "stuck waiting for the network", and "waiting for the user to type the next instruction" look identical — so the watchdog only resumes when it can prove the agent is gone (dead pid), or when the agent itself reports the interruption. The agent's own contract: try to recover on your own first, and callreport_interruptionwhen you give up — the watchdog then takes over with its own retry budget and backoff.
Task state machine
REGISTERED → RUNNING → INTERRUPTED
↓ ↓ ↓
└──────────┴──→ RECOVERING → RUNNING
↓
COMPLETED
or BLOCKED (exhausted)
or CANCELLED (human)MCP tools (7)
Tool | Description |
| Register a task for monitoring |
| Heartbeat / progress report |
| Persist verified progress (files touched, steps done, next steps) |
| Report an error or crash |
| Query full task state + event log |
| Mark complete — requires evidence of work |
| Cancel and stop recovery |
Configuration
All settings are environment variables (copy .env.example → .env if you use a dotenv loader; both uar-mcp and uar-watchdog must see the same values):
Variable | Default | Description |
|
| SQLite database shared by MCP + watchdog (must match between the two processes) |
| (empty = unrestricted) | Comma-separated root dirs; tasks outside are rejected |
|
| Global recovery killswitch |
|
| Heartbeat considered stale after 10 minutes |
|
| Max simultaneous recoveries |
|
| Hard runtime cap per recovery launch |
|
| Retry budget per task |
|
| Initial backoff between retries |
|
| Backoff cap |
|
| Recovery ownership lease |
|
| Watchdog polling interval |
|
|
|
| (none) | Optional JSON log file |
|
| OpenCode binary path |
|
| Claude Code binary path |
| (empty) | Resume template, e.g. |
| (empty) | New-session template, e.g. |
Running the watchdog as a service
macOS (launchd): copy
launchd/com.github.universal-agent-recovery.plistto~/Library/LaunchAgents/, adjust the paths, thenlaunchctl load ....Linux (systemd): create a user unit running
uar-watchdogwith the desiredRECOVERY_*environment.Windows: use a scheduled task (
schtasks /create ... /sc onstart) or a service wrapper.
Windows notes
npm shims (
opencode.cmd,claude.cmd) cannot be spawned directly by Node. Point the env at the real.exe:
setx OPENCODE_BIN "C:\path\to\nodejs\node_modules\@opencode\cli\bin\opencode.exe"Process-tree cancellation uses
taskkill /T /Fautomatically;tasklistis the process-health fallback.
Supported agents
Agent | Resume flag | Session inspection | Completion detection | Status |
OpenCode |
|
| No (verified via MCP) | ✅ Tier 1 validated |
Claude Code |
| No documented CLI |
| ✅ Tier 1 validated |
Generic CLI | Template-driven | No | No | ✅ Available |
Security
Working directories are validated against
RECOVERY_ALLOWED_DIRS.Agent processes are launched with argument arrays only (
shell: false) — no command injection from task metadata.Credential-like environment variables (
*TOKEN*,*SECRET*,*PASSWORD*,*CREDENTIAL*,*API_KEY*, ...) are stripped from agent processes; provider keys agent CLIs need (e.g.ANTHROPIC_API_KEY) are preserved via an explicit allowlist.API keys / tokens are never logged (structured logger redacts secrets).
RECOVERY_ENABLED=falseis the global killswitch.
Troubleshooting
Symptom | Likely cause | Fix |
Task not recovered |
| Set to |
"Recovery disabled" in logs | Global switch off |
|
Task stuck in RECOVERING | Watchdog died mid-recovery |
|
Agent resumes but task stays INTERRUPTED | Watchdog not running | Start |
Slow agents restarted |
| Increase it (default 10 min) |
| Binary not resolvable | Set |
"SQLite database is locked"
Another uar-mcp / uar-watchdog process holds a long write transaction, or the database
lives on a network filesystem (NFS/SMB — WAL mode requires local disk). Steps:
Check for stale processes:
ps aux | grep uar-and kill leftovers.Inspect the current state read-only:
uar-state(shows tasks, lease holders, retry counts).Confirm both processes point at the same
RECOVERY_DB_PATH.Move
RECOVERY_DB_PATHto a local disk if it is on a network mount.
"Task 'X' already exists (state: ...)"
Task IDs are unique forever, including terminal states (COMPLETED/CANCELLED/BLOCKED).
Use a new ID for a fresh run, or call cancel_task/mark_completed on the existing one.
"Task is BLOCKED; interruption not accepted"
The task exhausted its retry budget (maxAttempts, default 5) or failed with a
non-recoverable error class. Inspect lastError / recent events:
uar-state --task <taskId> # includes the last 50 eventsThen either fix the underlying problem and register a new task, or cancel it. There is currently no "unblock" tool — re-registering is intentional friction.
"outside the configured allowed directories"
RECOVERY_ALLOWED_DIRS is set and the task's working directory is outside every root.
Add the project root to the comma-separated list (both uar-mcp and uar-watchdog
must see the same value).
Config warnings at startup
Invalid numeric env values (e.g. RECOVERY_MAX_ATTEMPTS=-3) and unknown log levels are
replaced by defaults with a configuration warning log line at startup — check the logs
if behavior doesn't match what you configured.
Debugging snapshot
uar-state # pretty JSON of everything
uar-state --db ./data/recovery.db # explicit database path
uar-state --task my-task # single task + last 50 events
uar-state --compact | jq '.tasksByState'The dump is read-only and safe to run while the MCP server and watchdog are live.
Known limitations
Claude Code session inspection: no documented non-interactive command to list sessions; an invalid session id falls back to a new session.
Session inspection failure vs. missing session: a CLI failure during inspection makes the watchdog defer (never drop session context on a hiccup).
Completion detection (OpenCode): no structured output; completion is verified via MCP
mark_completed, not process exit.Generic CLI adapter: disabled unless templates are explicitly configured.
Documentation
Document | Content |
System architecture and design principles | |
MCP tool contracts and schemas | |
Use cases and scenarios | |
Recovery workflow details | |
Source code structure guide |
Development
npm install
npm run lint # ESLint
npm run typecheck # tsc --noEmit
npm test # unit + integration tests
npm run test:coverage # same tests + V8 coverage report
npm run build # compile to dist/Current coverage (V8): ~76% statements / ~71% branches overall; storage core
(src/storage) at ~90% statements. The thinner areas are the adapter binaries'
process plumbing (covered mainly by integration tests) and the uar-state CLI
(covered at the dumpState function level).
Integration tests against a real OpenCode binary run automatically when the binary exists; the live end-to-end test (needs provider credentials) is opt-in:
UAR_INTEGRATION=1 npm testProject structure
universal-agent-recovery/
├── bin/ # CLI shims: uar-mcp, uar-watchdog, uar-state
├── src/
│ ├── core/ # Types, state machine, error classifier, logger
│ ├── storage/ # SQLite, task/event/attempt repositories, leader lock
│ ├── adapters/ # OpenCode, Claude Code, Generic CLI, Mock (testing)
│ ├── mcp/ # MCP server (7 tools, stdio transport) + entry point
│ ├── watchdog/ # Supervisor, monitor, recovery policy, instructions
│ ├── cli/ # uar-state: read-only JSON state dump for debugging
│ └── examples/ # Demo script
├── docs/ # Design documents
├── tests/ # Unit + integration tests
└── launchd/ # macOS launchd plistLicense
Available Tools
7 toolscancel_taskCancel TaskC
Cancel a task and stop any further recovery attempts for it.
Inputs: taskId (required), reason.
get_task_statusGet Task StatusB
Get full task status: state, progress, checkpoint, recovery attempts, recent events.
Inputs: taskId (required), includeEvents.
mark_completedMark CompletedA
Mark a task completed after verifying the final state. Requires a verification note; completion is never inferred from process exit.
Inputs: taskId (required), verification (required).
register_taskRegister TaskA
Register a coding-agent task for monitoring and automatic recovery. The agent (or its launcher) calls this when starting a task so the watchdog can resume it after interruptions.
Inputs: taskId (required), adapterId (required), description (required), workingDirectory (required), +4 more.
report_interruptionReport InterruptionB
Report an error or interruption for a task. The watchdog verifies and schedules recovery.
Inputs: error (required), taskId (required), exitCode.
report_progressReport ProgressB
Report task progress (acts as a heartbeat). Keeps the watchdog from considering the task stale.
Inputs: taskId (required), progress (required).
save_checkpointSave CheckpointA
Persist verified progress so a new session can continue the task after a restart. Include concrete details: steps completed, files touched, next steps. Do not paste raw last output.
Inputs: taskId (required), summary (required), details, verified.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Each tool maps to a distinct lifecycle action, but report_progress (heartbeat) and save_checkpoint (durable state) are close enough that an agent could misuse one for the other; the descriptions do clarify the difference. register_task vs report_interruption vs mark_completed are clearly separated by intent.
All seven tools follow a strict snake_case verb_noun pattern (register_task, report_progress, save_checkpoint, report_interruption, get_task_status, mark_completed, cancel_task). No deviations or mixed conventions.
Seven tools cleanly covers the register→progress→checkpoint→recover→complete/cancel lifecycle without redundancy. Each tool earns its place in the watchdog workflow.
Core task lifecycle is fully covered, including recovery and terminal states. Minor gap: no way to enumerate or query multiple tasks (no list_tasks) and no explicit manual recovery trigger, though the watchdog handles recovery automatically.
Related MCP Connectors
Checkpoint and resume for AI agent runs, so crashed runs pick up where they left off.
Agent checkpoints. Resume after context resets and handoffs with retry-safe, versioned saves.
Task tracking built for coding agents. Work is leased, so two agents never take the same SubTask.
Watchdog for unattended AI agents: alerts, evidence checks and a verifiable proof per run.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides operational continuity for AI coding agents, preserving task state, decisions, checkpoints, and project context across sessions and model switches via MCP.1Apache 2.0
- AlicenseAqualityCmaintenanceEnables agents to monitor token/usage limits and persist work checkpoints, allowing them to pause, resume, and track progress across sessions.5MIT

genpark-long-horizonofficial
AlicenseNot gradedqualityBmaintenanceEnables long-horizon autonomous task checkpointing and resumption through cryptographic event-sourced state persistence, idempotency key deduplication, timeout heartbeats, human-in-the-loop pause/resume tokens, and fail-safe recovery.7MIT- AlicenseNot gradedqualityNot gradedmaintenanceEnables agents to persist and resume long-horizon tasks using cryptographic event-sourced checkpoints, idempotency deduplication, scheduled heartbeats, pause/resume tokens, and fail-safe recovery.MIT