How to eliminate "HTTP 401: Invalid bearer token" errors with automatic token refresh
"An ounce of prevention is worth a pound of cure." - Benjamin Franklin
TL;DR
The Problem: Moltbot stops working with "HTTP 401 authentication_error: Invalid bearer token" after a few hours.
note: Clawdbot was just renamed to Moltbot because Anthropic (makers of Claude Code) came after them for supposed copyright infringement.
The Solution: Set up automatic hourly token sync from Claude Code CLI.
Quick Setup (5 minutes):
# Create sync script
mkdir -p ~/.moltbot/scripts ~/.moltbot/logs
cat > ~/.moltbot/scripts/sync-token.sh << 'EOF'
#!/bin/bash
moltbot models status >/dev/null 2>&1
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Token sync triggered" >> ~/.moltbot/logs/token-sync.log
EOF
# Make executable
chmod +x ~/.moltbot/scripts/sync-token.sh
# Add to crontab (runs every hour)
(crontab -l 2>/dev/null; echo "0 * * * * $HOME/.moltbot/scripts/sync-token.sh") | crontab -
# Test it
~/.moltbot/scripts/sync-token.sh
Result: No more token expiration errors, ever.
Read if: You want to understand how OAuth tokens work, alternative solutions, or need troubleshooting help.
Table of Contents
- The Problem: Why Tokens Expire
- Understanding Token Types
- Solution 1: Automatic Hourly Sync
- Solution 2: Manual Refresh When Needed
- Solution 3: Switch to API Key
- Verification & Monitoring
- Troubleshooting
- Best Practices
- Conclusion
The Problem: Why Tokens Expire
The Error
HTTP 401: authentication_error: Invalid bearer token
(request_id: req_011CXXokZqEMrWu9JuAPEB9x)
This appears when:
- You haven't used Moltbot in several hours
- Claude Code CLI token refreshed but Moltbot didn't sync
- OAuth access token expired (typically 12 hours)
What Happens
When you authenticate Moltbot with Claude Code subscription:
- Initial auth: Moltbot copies OAuth token from
~/.claude/.credentials.json - Claude Code refreshes: Token updates in Claude Code (automatic)
- Moltbot doesn't know: Still using old expired token
- API calls fail: 401 authentication error
Why This Happens
Moltbot and Claude Code are separate processes:
- Claude Code CLI manages its own OAuth refresh
- Moltbot has a copy of the token, not a reference
- When Claude Code gets a fresh token, Moltbot keeps using the old one
Think of it like photocopying a driver's license - if the original gets renewed, your photocopy is still expired.
Understanding Token Types
Before choosing a solution, understand your authentication method:
OAuth Token (Subscription Users)
What it is: Temporary access token from Claude.ai login
Characteristics:
- ✅ Uses your Claude subscription (Pro/Max/Code)
- ✅ No API key needed
- ✅ Free (included in subscription)
- ❌ Expires every 12 hours
- ❌ Requires periodic refresh
Location:
- Claude Code:
~/.claude/.credentials.json - Moltbot:
~/.moltbot/agents/main/agent/auth-profiles.json
Who should use this: Claude subscription users who want to use their plan's rate limits instead of paying for API usage.
Setup Token
What it is: Special token generated by claude setup-token command
Characteristics:
- ✅ Uses Claude subscription
- ✅ Easier to share across machines
- ❌ Still expires (like OAuth)
- ❌ Manual refresh needed
How to generate:
claude setup-token
# Copy output and paste when prompted:
moltbot models auth paste-token --provider anthropic
API Key
What it is: Direct Anthropic API key (pay-per-use)
Characteristics:
- ✅ Never expires
- ✅ No refresh needed
- ✅ Works everywhere
- ❌ Costs money per token
- ❌ Separate from subscription
Who should use this: Heavy users who prefer predictable per-token pricing over subscription limits.
Solution 1: Automatic Hourly Sync
Best for: Most users who want "set it and forget it" reliability.
How It Works
Every hour (00:00, 01:00, 02:00...)
↓
Run: moltbot models status
↓
Moltbot checks: Is Claude Code token newer?
↓
If yes: Copy fresh token from ~/.claude/.credentials.json
↓
If no: Do nothing
↓
Log sync activity
Step-by-Step Setup
1. Create Sync Script
mkdir -p ~/.moltbot/scripts ~/.moltbot/logs
cat > ~/.moltbot/scripts/sync-token.sh << 'EOF'
#!/bin/bash
# Auto-sync Moltbot token from Claude Code CLI
# Prevents "Invalid bearer token" errors
# Trigger Moltbot's built-in sync mechanism
moltbot models status >/dev/null 2>&1
# Log the sync for monitoring
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Token sync triggered" >> ~/.moltbot/logs/token-sync.log
EOF
2. Make Executable
chmod +x ~/.moltbot/scripts/sync-token.sh
3. Test It
# Run manually to verify
~/.moltbot/scripts/sync-token.sh
# Check log
cat ~/.moltbot/logs/token-sync.log
# Expected output:
# [2026-01-27 06:50:29] Token sync triggered
4. Add to Crontab
# Add cron job (runs every hour)
(crontab -l 2>/dev/null; echo "0 * * * * $HOME/.moltbot/scripts/sync-token.sh") | crontab -
# Verify cron job was added
crontab -l | grep moltbot
# Expected output:
# 0 * * * * /home/youruser/.moltbot/scripts/sync-token.sh
What Gets Synced
When moltbot models status runs, it automatically:
- Reads
~/.claude/.credentials.json - Extracts current OAuth access token
- Compares with Moltbot's stored token
- Updates if different
- Refreshes OAuth credentials if needed
No manual intervention required!
Frequency Options
Every hour (recommended):
0 * * * * $HOME/.moltbot/scripts/sync-token.sh
Every 30 minutes (ultra-safe):
*/30 * * * * $HOME/.moltbot/scripts/sync-token.sh
Every 6 hours (minimal):
0 */6 * * * $HOME/.moltbot/scripts/sync-token.sh
Trade-offs:
- More frequent = more reliable, slightly more system overhead
- Less frequent = fewer cron runs, slightly higher risk
Hourly is the sweet spot for most users.
Solution 2: Manual Refresh When Needed
Best for: Users who don't want cron jobs or use Moltbot sporadically.
When to Use
- You get a 401 error
- After not using Moltbot for several hours
- After Claude Code CLI session refresh
Quick Manual Sync
Option A: Using Moltbot CLI
moltbot models status
Option B: Direct Token Copy
# Extract token from Claude Code
NEW_TOKEN=$(jq -r '.claudeAiOauth.accessToken' ~/.claude/.credentials.json)
# Update Moltbot auth file
jq --arg token "$NEW_TOKEN" \
'.profiles."anthropic:default".token = $token' \
~/.moltbot/agents/main/agent/auth-profiles.json > /tmp/auth.json
# Apply update
mv /tmp/auth.json ~/.moltbot/agents/main/agent/auth-profiles.json
Create an Alias
Add to ~/.bashrc or ~/.zshrc:
alias moltbot-refresh='moltbot models status && echo "Token refreshed!"'
Then just run:
moltbot-refresh
Pros & Cons
Pros:
- ✅ No cron job needed
- ✅ Full control over when sync happens
- ✅ No background processes
Cons:
- ❌ Must remember to run manually
- ❌ Still get 401 errors if you forget
- ❌ Interrupts workflow when token expires
Solution 3: Switch to API Key
Best for: Heavy users who hit subscription rate limits or want predictable per-token pricing.
Why Consider This
Use API key if:
- You consistently hit Claude subscription rate limits
- You need guaranteed availability (no rate limit resets)
- You prefer paying per token over subscription caps
- You're building production applications
Stick with OAuth if:
- You're within subscription limits
- Cost per token matters more than availability
- You're using Moltbot personally (not production)
Cost Comparison
With OAuth (subscription):
- Cost: $0 (included in subscription)
- Rate limits: Plan-dependent (e.g., 100 requests/5 hours)
- Overage: Pay-per-use if exceeded
With API key:
- Cost: $3/$15 per million tokens (Sonnet 4.5)
- Rate limits: Much higher (tier-based)
- Overage: No concept of "overage" - just usage
Break-even example (Sonnet 4.5):
Monthly usage: 10M input + 1M output tokens
API cost: (10 × $3) + (1 × $15) = $45/month
Claude Pro subscription: $20/month
Claude Max subscription: $40/month (includes Code)
API makes sense if:
- You're maxing out Max subscription AND
- Paying significant overage charges
Setup with API Key
# Get API key from https://console.anthropic.com/settings/keys
# Configure Moltbot
moltbot models auth paste-token --provider anthropic
# When prompted, paste your API key
# Verify
moltbot models list
# Should show "Auth: yes" with no expiration warnings
Benefit: API keys never expire. No token refresh needed!
Verification & Monitoring
Check Current Token Status
# View auth profiles
cat ~/.moltbot/agents/main/agent/auth-profiles.json | jq '.profiles."anthropic:default"'
Output:
{
"type": "token",
"provider": "anthropic",
"token": "sk-ant-oat01-9mAk53A6qaHf7r5c..."
}
Check Token Expiration (OAuth only)
# View Claude Code credentials with expiration
cat ~/.claude/.credentials.json | jq '.claudeAiOauth | {expires: .expiresAt}'
Output:
{
"expires": 1769546430398
}
Convert to human-readable:
# On macOS/Linux
date -r $(( $(jq -r '.claudeAiOauth.expiresAt' ~/.claude/.credentials.json) / 1000 ))
Monitor Sync Activity
View sync log:
tail -f ~/.moltbot/logs/token-sync.log
Check when last sync happened:
tail -1 ~/.moltbot/logs/token-sync.log
Count sync events today:
grep "$(date +%Y-%m-%d)" ~/.moltbot/logs/token-sync.log | wc -l
Test Authentication
# Quick test
moltbot agent --local --session-id auth-test -m "Authentication test"
# Expected output: Normal response (not 401 error)
Verify Cron Job
List cron jobs:
crontab -l
Check cron is running:
# View cron logs (varies by system)
# Ubuntu/Debian:
grep CRON /var/log/syslog | tail -5
# macOS:
log show --predicate 'process == "cron"' --last 1h
Troubleshooting
Still Getting 401 Errors
Diagnosis:
# 1. Check if cron job exists
crontab -l | grep moltbot
# 2. Check if script is executable
ls -l ~/.moltbot/scripts/sync-token.sh
# 3. Test script manually
~/.moltbot/scripts/sync-token.sh
# 4. Check for errors in sync
moltbot models status 2>&1 | grep -i error
Common fixes:
Cron not running:
# Start cron service (Linux)
sudo systemctl start cron
# macOS (cron runs automatically)
# Make sure you allowed cron in System Preferences > Privacy
Script has wrong line endings (Windows/WSL):
# Fix with dos2unix
dos2unix ~/.moltbot/scripts/sync-token.sh
# Or with sed
sed -i 's/\r$//' ~/.moltbot/scripts/sync-token.sh
Script has wrong path in cron:
# Update cron job with full path
crontab -e
# Change to:
0 * * * * /home/YOURUSERNAME/.moltbot/scripts/sync-token.sh
Tokens Mismatched
If Claude Code and Moltbot have different tokens:
# Force sync immediately
moltbot models status
# Verify they match
CLAUDE_TOKEN=$(jq -r '.claudeAiOauth.accessToken' ~/.claude/.credentials.json)
MOLTBOT_TOKEN=$(jq -r '.profiles."anthropic:default".token' ~/.moltbot/agents/main/agent/auth-profiles.json)
if [ "$CLAUDE_TOKEN" = "$MOLTBOT_TOKEN" ]; then
echo "✓ Tokens match"
else
echo "✗ Tokens differ - sync needed"
fi
Sync Log Not Creating
# Verify directory exists
mkdir -p ~/.moltbot/logs
# Check permissions
ls -ld ~/.moltbot/logs
# Test log creation
echo "test" >> ~/.moltbot/logs/token-sync.log
cat ~/.moltbot/logs/token-sync.log
Cron Running But Not Working
Check cron environment:
Cron has a minimal environment. Your script might need:
# Update sync-token.sh with full paths:
#!/bin/bash
export PATH="/usr/local/bin:/usr/bin:/bin:$HOME/.local/bin"
# Use full path to moltbot
$HOME/.local/bin/moltbot models status >/dev/null 2>&1
# Rest of script...
Find moltbot path:
which moltbot
# Use this full path in your script
Claude Code Not Installed
If ~/.claude/.credentials.json doesn't exist:
# Install Claude Code CLI
npm install -g @anthropic-ai/claude-code
# Login
claude --login
# Verify credentials exist
ls -l ~/.claude/.credentials.json
Best Practices
1. Monitor Sync Health
Create a weekly check:
# Add to crontab (runs Monday at 9am)
0 9 * * 1 tail -n 168 ~/.moltbot/logs/token-sync.log | wc -l | \
awk '{if($1<150) print "WARNING: Only "$1" syncs last week (expected 168)"}' | \
mail -s "Moltbot sync health" you@example.com
2. Backup Auth Profiles
Before modifying:
# Automatic backup in sync script
cp ~/.moltbot/agents/main/agent/auth-profiles.json \
~/.moltbot/agents/main/agent/auth-profiles.json.backup.$(date +%s)
3. Log Rotation
Prevent sync log from growing forever:
# Add to monthly cron
0 0 1 * * gzip -9 ~/.moltbot/logs/token-sync.log && \
> ~/.moltbot/logs/token-sync.log
4. Use Monitoring Tools
Simple monitoring:
# Create ~/bin/check-moltbot
#!/bin/bash
if moltbot agent --local --session-id health -m "health check" 2>&1 | grep -q "401"; then
echo "ERROR: Moltbot auth failed!"
exit 1
else
echo "OK: Moltbot healthy"
exit 0
fi
Run via cron:
# Alert if auth fails (every 6 hours)
0 */6 * * * ~/bin/check-moltbot || mail -s "Moltbot down" you@example.com
5. Document Your Setup
Create a reference file:
cat > ~/.moltbot/TOKEN_REFRESH_README.md << 'EOF'
# Token Refresh Setup
## Current Configuration
- Method: Automatic hourly sync via cron
- Cron schedule: 0 * * * *
- Script location: ~/.moltbot/scripts/sync-token.sh
- Log location: ~/.moltbot/logs/token-sync.log
## Manual Refresh
If needed: `moltbot models status`
## Troubleshooting
1. Check cron: `crontab -l | grep moltbot`
2. Test script: `~/.moltbot/scripts/sync-token.sh`
3. View logs: `tail ~/.moltbot/logs/token-sync.log`
## Last Updated
$(date)
EOF
Conclusion
Token expiration doesn't have to break your Moltbot workflow. With automatic hourly sync:
What You Get
- ✅ Zero maintenance: Set up once, works forever
- ✅ No more 401 errors: Tokens stay fresh automatically
- ✅ Peace of mind: Runs silently in background
- ✅ Full monitoring: Logs track every sync
- ✅ Easy troubleshooting: Clear error messages
The Complete Setup (Copy-Paste)
# 1. Create script
mkdir -p ~/.moltbot/scripts ~/.moltbot/logs
cat > ~/.moltbot/scripts/sync-token.sh << 'EOF'
#!/bin/bash
moltbot models status >/dev/null 2>&1
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Token sync triggered" >> ~/.moltbot/logs/token-sync.log
EOF
# 2. Make executable
chmod +x ~/.moltbot/scripts/sync-token.sh
# 3. Add to crontab
(crontab -l 2>/dev/null; echo "0 * * * * $HOME/.moltbot/scripts/sync-token.sh") | crontab -
# 4. Test
~/.moltbot/scripts/sync-token.sh && tail -1 ~/.moltbot/logs/token-sync.log
# 5. Verify cron
crontab -l | grep moltbot
That's it! Your Moltbot will never have authentication issues again.
Quick Reference Card
┌─────────────────────────────────────────────┐
│ Moltbot Token Refresh Quick Reference │
├─────────────────────────────────────────────┤
│ Manual sync: │
│ moltbot models status │
│ │
│ Check auth: │
│ moltbot models list │
│ │
│ View sync log: │
│ tail ~/.moltbot/logs/token-sync.log │
│ │
│ Test script: │
│ ~/.moltbot/scripts/sync-token.sh │
│ │
│ Check cron: │
│ crontab -l | grep moltbot │
└─────────────────────────────────────────────┘
Resources
Documentation
Related Guides
Community
Last updated: January 27, 2026
Moltbot version: 2026.1.24-3
Claude Code version: 2.1.19