MCPcopy Index your code
hub / github.com/cloudflare/moltworker

github.com/cloudflare/moltworker @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
114 symbols 268 edges 38 files 23 documented · 20% updated 58d ago★ 9,91563 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

OpenClaw on Cloudflare Workers

Run OpenClaw (formerly Moltbot, formerly Clawdbot) personal AI assistant in a Cloudflare Sandbox.

moltworker architecture

Experimental: This is a proof of concept demonstrating that OpenClaw can run in Cloudflare Sandbox. It is not officially supported and may break without notice. Use at your own risk.

Deploy to Cloudflare

Requirements

The following Cloudflare features used by this project have free tiers: - Cloudflare Access (authentication) - Browser Rendering (for browser navigation) - AI Gateway (optional, for API routing/analytics) - R2 Storage (optional, for persistence)

Container Cost Estimate

This project uses a standard-1 Cloudflare Container instance (1/2 vCPU, 4 GiB memory, 8 GB disk). Below are approximate monthly costs assuming the container runs 24/7, based on Cloudflare Containers pricing:

Resource Provisioned Monthly Usage Included Free Overage Approx. Cost
Memory 4 GiB 2,920 GiB-hrs 25 GiB-hrs 2,895 GiB-hrs ~$26/mo
CPU (at ~10% utilization) 1/2 vCPU ~2,190 vCPU-min 375 vCPU-min ~1,815 vCPU-min ~$2/mo
Disk 8 GB 5,840 GB-hrs 200 GB-hrs 5,640 GB-hrs ~$1.50/mo
Workers Paid plan $5/mo
Total ~$34.50/mo

Notes: - CPU is billed on active usage only, not provisioned capacity. The 10% utilization estimate is a rough baseline for a lightly-used personal assistant; your actual cost will vary with usage. - Memory and disk are billed on provisioned capacity for the full time the container is running. - To reduce costs, configure SANDBOX_SLEEP_AFTER (e.g., 10m) so the container sleeps when idle. A container that only runs 4 hours/day would cost roughly ~$5-6/mo in compute on top of the $5 plan fee. - Network egress, Workers/Durable Objects requests, and logs are additional but typically minimal for personal use. - See the instance types table for other options (e.g., lite at 256 MiB/$0.50/mo memory or standard-4 at 12 GiB for heavier workloads).

What is OpenClaw?

OpenClaw (formerly Moltbot, formerly Clawdbot) is a personal AI assistant with a gateway architecture that connects to multiple chat platforms. Key features:

  • Control UI - Web-based chat interface at the gateway
  • Multi-channel support - Telegram, Discord, Slack
  • Device pairing - Secure DM authentication requiring explicit approval
  • Persistent conversations - Chat history and context across sessions
  • Agent runtime - Extensible AI capabilities with workspace and skills

This project packages OpenClaw to run in a Cloudflare Sandbox container, providing a fully managed, always-on deployment without needing to self-host. Optional R2 storage enables persistence across container restarts.

Architecture

moltworker architecture

Quick Start

Cloudflare Sandboxes are available on the Workers Paid plan.

# Install dependencies
npm install

# Set your API key (direct Anthropic access)
npx wrangler secret put ANTHROPIC_API_KEY

# Or use Cloudflare AI Gateway instead (see "Optional: Cloudflare AI Gateway" below)
# npx wrangler secret put CLOUDFLARE_AI_GATEWAY_API_KEY
# npx wrangler secret put CF_AI_GATEWAY_ACCOUNT_ID
# npx wrangler secret put CF_AI_GATEWAY_GATEWAY_ID

# Generate and set a gateway token (required for remote access)
# Save this token - you'll need it to access the Control UI
export MOLTBOT_GATEWAY_TOKEN=$(openssl rand -hex 32)
echo "Your gateway token: $MOLTBOT_GATEWAY_TOKEN"
echo "$MOLTBOT_GATEWAY_TOKEN" | npx wrangler secret put MOLTBOT_GATEWAY_TOKEN

# Deploy
npm run deploy

After deploying, open the Control UI with your token:

https://your-worker.workers.dev/?token=YOUR_GATEWAY_TOKEN

Replace your-worker with your actual worker subdomain and YOUR_GATEWAY_TOKEN with the token you generated above.

Note: The first request may take 1-2 minutes while the container starts.

Important: You will not be able to use the Control UI until you complete the following steps. You MUST: 1. Set up Cloudflare Access to protect the admin UI 2. Pair your device via the admin UI at /_admin/

You'll also likely want to enable R2 storage so your paired devices and conversation history persist across container restarts (optional but recommended).

Setting Up the Admin UI

To use the admin UI at /_admin/ for device management, you need to: 1. Enable Cloudflare Access on your worker 2. Set the Access secrets so the worker can validate JWTs

1. Enable Cloudflare Access on workers.dev

The easiest way to protect your worker is using the built-in Cloudflare Access integration for workers.dev:

  1. Go to the Workers & Pages dashboard
  2. Select your Worker (e.g., moltbot-sandbox)
  3. In Settings, under Domains & Routes, in the workers.dev row, click the meatballs menu (...)
  4. Click Enable Cloudflare Access
  5. Copy the values shown in the dialog (you'll need the AUD tag later). Note: The "Manage Cloudflare Access" link in the dialog may 404 — ignore it.
  6. To configure who can access, go to Zero Trust in the Cloudflare dashboard sidebar → AccessApplications, and find your worker's application:
  7. Add your email address to the allow list
  8. Or configure other identity providers (Google, GitHub, etc.)
  9. Copy the Application Audience (AUD) tag from the Access application settings. This will be your CF_ACCESS_AUD in Step 2 below

2. Set Access Secrets

After enabling Cloudflare Access, set the secrets so the worker can validate JWTs:

# Your Cloudflare Access team domain (e.g., "myteam.cloudflareaccess.com")
npx wrangler secret put CF_ACCESS_TEAM_DOMAIN

# The Application Audience (AUD) tag from your Access application that you copied in the step above
npx wrangler secret put CF_ACCESS_AUD

You can find your team domain in the Zero Trust Dashboard under Settings > Custom Pages (it's the subdomain before .cloudflareaccess.com).

3. Redeploy

npm run deploy

Now visit /_admin/ and you'll be prompted to authenticate via Cloudflare Access before accessing the admin UI.

Alternative: Manual Access Application

If you prefer more control, you can manually create an Access application:

  1. Go to Cloudflare Zero Trust Dashboard
  2. Navigate to Access > Applications
  3. Create a new Self-hosted application
  4. Set the application domain to your Worker URL (e.g., moltbot-sandbox.your-subdomain.workers.dev)
  5. Add paths to protect: /_admin/*, /api/*, /debug/*
  6. Configure your desired identity providers (e.g., email OTP, Google, GitHub)
  7. Copy the Application Audience (AUD) tag and set the secrets as shown above

Local Development

For local development, create a .dev.vars file with:

DEV_MODE=true               # Skip Cloudflare Access auth + bypass device pairing
DEBUG_ROUTES=true           # Enable /debug/* routes (optional)

Authentication

By default, moltbot uses device pairing for authentication. When a new device (browser, CLI, etc.) connects, it must be approved via the admin UI at /_admin/.

Device Pairing

  1. A device connects to the gateway
  2. The connection is held pending until approved
  3. An admin approves the device via /_admin/
  4. The device is now paired and can connect freely

This is the most secure option as it requires explicit approval for each device.

Gateway Token (Required)

A gateway token is required to access the Control UI when hosted remotely. Pass it as a query parameter:

https://your-worker.workers.dev/?token=YOUR_TOKEN
wss://your-worker.workers.dev/ws?token=YOUR_TOKEN

Note: Even with a valid token, new devices still require approval via the admin UI at /_admin/ (see Device Pairing above).

For local development only, set DEV_MODE=true in .dev.vars to skip Cloudflare Access authentication and enable allowInsecureAuth (bypasses device pairing entirely).

Persistent Storage (R2)

By default, moltbot data (configs, paired devices, conversation history) is lost when the container restarts. To enable persistent storage across sessions, configure R2:

1. Create R2 API Token

  1. Go to R2 > Overview in the Cloudflare Dashboard
  2. Click Manage R2 API Tokens
  3. Create a new token with Object Read & Write permissions
  4. Select the moltbot-data bucket (created automatically on first deploy)
  5. Copy the Access Key ID and Secret Access Key

2. Set Secrets

# R2 Access Key ID
npx wrangler secret put R2_ACCESS_KEY_ID

# R2 Secret Access Key
npx wrangler secret put R2_SECRET_ACCESS_KEY

# Your Cloudflare Account ID
npx wrangler secret put CF_ACCOUNT_ID

To find your Account ID: Go to the Cloudflare Dashboard, click the three dots menu next to your account name, and select "Copy Account ID".

How It Works

R2 storage uses a backup/restore approach for simplicity:

On container startup: - If R2 is mounted and contains backup data, it's restored to the moltbot config directory - OpenClaw uses its default paths (no special configuration needed)

During operation: - A cron job runs every 5 minutes to sync the moltbot config to R2 - You can also trigger a manual backup from the admin UI at /_admin/

In the admin UI: - When R2 is configured, you'll see "Last backup: [timestamp]" - Click "Backup Now" to trigger an immediate sync

Without R2 credentials, moltbot still works but uses ephemeral storage (data lost on container restart).

Container Lifecycle

By default, the sandbox container stays alive indefinitely (SANDBOX_SLEEP_AFTER=never). This is recommended because cold starts take 1-2 minutes.

To reduce costs for infrequently used deployments, you can configure the container to sleep after a period of inactivity:

npx wrangler secret put SANDBOX_SLEEP_AFTER
# Enter: 10m (or 1h, 30m, etc.)

When the container sleeps, the next request will trigger a cold start. If you have R2 storage configured, your paired devices and data will persist across restarts.

Admin UI

admin ui

Access the admin UI at /_admin/ to: - R2 Storage Status - Shows if R2 is configured, last backup time, and a "Backup Now" button - Restart Gateway - Kill and restart the moltbot gateway process - Device Pairing - View pending requests, approve devices individually or all at once, view paired devices

The admin UI requires Cloudflare Access authentication (or DEV_MODE=true for local development).

Debug Endpoints

Debug endpoints are available at /debug/* when enabled (requires DEBUG_ROUTES=true and Cloudflare Access):

  • GET /debug/processes - List all container processes
  • GET /debug/logs?id=<process_id> - Get logs for a specific process
  • GET /debug/version - Get container and moltbot version info

Optional: Chat Channels

Telegram

npx wrangler secret put TELEGRAM_BOT_TOKEN
npm run deploy

Discord

npx wrangler secret put DISCORD_BOT_TOKEN
npm run deploy

Slack

npx wrangler secret put SLACK_BOT_TOKEN
npx wrangler secret put SLACK_APP_TOKEN
npm run deploy

Optional: Browser Automation (CDP)

This worker includes a Chrome DevTools Protocol (CDP) shim that enables browser automation capabilities. This allows OpenClaw to control a headless browser for tasks like web scraping, screenshots, and automated testing.

Setup

  1. Set a shared secret for authentication:
npx wrangler secret put CDP_SECRET
# Enter a secure random string
  1. Set your worker's public URL:
npx wrangler secret put WORKER_URL
# Enter: https://your-worker.workers.dev
  1. Redeploy:
npm run deploy

Endpoints

Endpoint Description
GET /cdp/json/version Browser version information
GET /cdp/json/list List available browser targets
GET /cdp/json/new Create a new browser target
WS /cdp/devtools/browser/{id} WebSocket connection for CDP commands

All endpoints require authentication via the ?secret=<CDP_SECRET> query parameter.

Built-in Skills

The container includes pre-installed skills in /root/clawd/skills/:

cloudflare-browser

Browser automation via the CDP shim. Requires CDP_SECRET and WORKER_URL to be set (see Browser Automation above).

Scripts: - screenshot.js - Capture a screenshot of a URL - video.js - Create a video from multiple URLs - cdp-client.js - Reusable CDP client library

Usage: ```bash

Screenshot

node /root/clawd/skills/cloudflare-brow

Extension points exported contracts — how you extend this code

CronJob (Interface)
* Minimal cron job shape we need from OpenClaw's jobs.json
src/cron/wake.ts
CDPRequest (Interface)
* CDP Message types
src/routes/cdp.ts
MockSandbox (Interface)
(no doc)
src/test-utils.ts
OpenClawEnv (Interface)
(no doc)
src/types.ts
PendingDevice (Interface)
(no doc)
src/client/api.ts
AccessMiddlewareOptions (Interface)
(no doc)
src/auth/middleware.ts
CronStoreFile (Interface)
(no doc)
src/cron/wake.ts
CDPSession (Interface)
* Session state for a CDP connection
src/routes/cdp.ts

Core symbols most depended-on inside this repo

createMockEnv
called by 25
src/test-utils.ts
findExistingGatewayProcess
called by 18
src/gateway/process.ts
redactSensitiveParams
called by 15
src/utils/logging.ts
buildEnvVars
called by 15
src/gateway/env.ts
createMockSandbox
called by 13
src/test-utils.ts
shouldWakeContainer
called by 13
src/cron/wake.ts
createAccessMiddleware
called by 9
src/auth/middleware.ts
send
called by 9
skills/cloudflare-browser/scripts/cdp-client.js

Shape

Function 92
Interface 19
Class 2
Method 1

Languages

TypeScript100%

Modules by API surface

src/routes/cdp.ts21 symbols
src/client/api.ts18 symbols
skills/cloudflare-browser/scripts/cdp-client.js12 symbols
src/client/pages/AdminPage.tsx9 symbols
src/persistence.ts8 symbols
src/test-utils.ts7 symbols
src/index.ts5 symbols
src/cron/wake.ts5 symbols
src/auth/middleware.ts5 symbols
src/gateway/process.ts4 symbols
skills/cloudflare-browser/scripts/video.js4 symbols
src/types.ts3 symbols

Dependencies from manifests, versioned

@cloudflare/sandbox0.7.20 · 1×
@cloudflare/vite-plugin1.0.0 · 1×
@cloudflare/workers-types4.20250109.0 · 1×
@types/node22.0.0 · 1×
@types/react19.0.0 · 1×
@types/react-dom19.0.0 · 1×
@vitejs/plugin-react4.3.0 · 1×
@vitest/coverage-v84.0.18 · 1×
croner9.1.0 · 1×
hono4.11.6 · 1×
jose6.0.0 · 1×

For agents

$ claude mcp add moltworker \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact