Skip to content
AILinkDeepTech
Go back
AI Agents

OpenClaw: Architecture, Gateway Routing, Sandboxed MCP Skills, and Multi-Channel Deployment

Abstract

Master OpenClaw: self-hosted gateway routing, Docker sandbox isolation, SKILL.md progressive disclosure, MCP servers, and multi-channel messaging deployment.

Figure 1: OpenClaw self-hosted runtime architecture. The unified Gateway daemon multiplexes messaging surfaces (Telegram, WhatsApp, Discord, Slack) to an LLM decision loop backed by sandboxed tool execution and local session memory.

Self-Hosted Agent Architecture vs. Cloud Assistants

Cloud-hosted personal assistants introduce severe operational and security constraints: third-party data retention, rigid rate limits, opaque telemetry, and an inability to execute native shell commands safely.

OpenClaw provides a modular, self-hosted agent runtime designed around a single-control-plane daemon. It decouples channel transport (Baileys, grammY, Discord.js) from the agent decision loop, enforcing strict isolation through containerized sandbox execution (Docker / OpenShell) and progressive skill injection (SKILL.md).


Architectural Comparison

Metric / DimensionHosted Cloud Assistants (ChatGPT / Claude)OpenClaw Self-Hosted Gateway
Data Locality & PrivacyRemote Cloud Processing100% Local / On-Premise Host Execution
Messaging Channel ReachWeb UI / Proprietary App Only20+ Protocols (WhatsApp, Telegram, Discord, Slack, IRC)
Tool Execution SecurityRemote MicroVM (Opaque)Configurable Docker / SSH Sandboxes with Network Isolation
Skill ExtensibilityCustom GPT Action PromptsStandardized SKILL.md Progressive Disclosure + MCP
Multi-Agent Session RoutingNot SupportedPer-Channel & Per-Workspace Session Isolation
Resource OverheadCloud Billing~150 MB RAM (Gateway Daemon)

System Architecture

flowchart TB subgraph SURFACES["Messaging Surfaces (Inbound / Outbound)"] TG["Telegram (grammY)"] WA["WhatsApp (Baileys)"] DC["Discord / Slack"] WEB["WebChat / Control UI"] end subgraph GATEWAY["OpenClaw Gateway Daemon (Port 18789)"] ROUTER["Session & Channel Router"] CTX["Context & Memory Compiler\n(AGENTS.md + Session SQLite)"] SKILLS["Skill Loader & Filter\n(Precedence Stack)"] ROUTER --> CTX ROUTER --> SKILLS end subgraph RUNTIME["LLM Decision Engine"] LLM["Foundation Model\n(Claude / GPT / Local Ollama)"] end subgraph EXEC["Execution Layer"] HOST["Host Execution\n(Main Session Only)"] DOCKER["Docker Sandbox Container\n(Non-Main Sessions)"] MCP["MCP Server Ecosystem\n(Filesystem, Web Search, DB)"] end SURFACES <-->|"Typed JSON-RPC / WS"| ROUTER CTX --> LLM SKILLS --> LLM LLM -->|"Tool Invocations"| EXEC EXEC -->|"Tool Output"| CTX

Figure 2: OpenClaw unified control plane. The Gateway daemon multiplexes inbound channel events, compiles the active session context with filtered skill definitions, and routes tool calls to either the host or isolated Docker sandboxes.


Core Components & Mechanics

1. Gateway Control Plane & Typed WebSocket Protocol

The Gateway runs as a long-lived Node.js process exposing a typed JSON-schema-validated WebSocket server on 127.0.0.1:18789. Inbound messages trigger an event-driven execution loop:

  1. Channel Normalization: Raw webhooks or polling events from Baileys, grammY, or Discord.js are parsed into a normalized InboundMessage payload.
  2. Session Key Resolution: The router maps the conversation to an isolated session key (main, tg:123456, group:dev-team).
  3. Context Assembly: The system prompt is constructed by concatenating persistent memory (SOUL.md, AGENTS.md), recent session history from SQLite, and active skill definitions.
  4. Tool Interception: If the model emits tool calls, the execution layer verifies authorization against the session’s sandbox policy before dispatching.

2. Progressive Disclosure Skill Specification (SKILL.md)

OpenClaw loads skills hierarchically based on the following precedence hierarchy:

Priority 1 (Highest):  <workspace>/skills/              (Workspace-local skills)
Priority 2:            <workspace>/.agents/skills/      (Project agent skills)
Priority 3:            ~/.agents/skills/                (Personal user skills)
Priority 4:            ~/.openclaw/skills/              (Managed skills)
Priority 5 (Lowest):   Bundled system skills

Each skill is declared as a Markdown document containing a YAML frontmatter header that defines gating constraints (required binaries, environment variables, OS platforms) and procedural instructions.


Implementation & Production Deployment

Step 1: Installation & Gateway Initialization

# 1. Install OpenClaw globally (Node.js >= 22 required)
npm install -g openclaw@latest

# 2. Run initial non-interactive setup
openclaw onboard --install-daemon

# 3. Verify daemon health
openclaw doctor

Step 2: Configuration Specification (openclaw.json5)

Create or update ~/.openclaw/openclaw.json with multi-channel routing, model failover chains, and Docker sandboxing:

{
  agents: {
    defaults: {
      model: {
        primary: "anthropic/claude-sonnet-4-6",
        fallbacks: ["openai/gpt-5.4", "ollama/qwen2.5:72b"],
      },
      workspace: "~/.openclaw/workspace",
      sandbox: {
        mode: "non-main",        // Enforce sandbox on all non-owner sessions
        scope: "agent",          // One dedicated container per agent
        backend: "docker",
        docker: {
          image: "node:24-bookworm-slim",
          network: "none",       // Zero egress network by default
          binds: [
            "~/.openclaw/workspace/shared:/home/sandbox/shared:rw"
          ],
        },
        tools: {
          allow: [
            "bash", "read", "write", "edit", "apply_patch",
            "sessions_list", "sessions_history", "sessions_send"
          ],
          deny: ["gateway", "nodes", "cron", "discord_admin"],
        },
      },
    },
  },
  channels: {
    telegram: {
      enabled: true,
      botToken: "${TELEGRAM_BOT_TOKEN}",
      dmPolicy: "pairing",       // Unknown senders must be paired
      allowFrom: ["tg:987654321"],
    },
    whatsapp: {
      enabled: true,
      allowFrom: ["+15550199283"],
    },
    discord: {
      enabled: true,
      botToken: "${DISCORD_BOT_TOKEN}",
      dmPolicy: "pairing",
    },
  },
  plugins: {
    entries: {
      mcp: {
        enabled: true,
        config: {
          servers: {
            "filesystem": {
              command: "npx",
              args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/sandbox/shared"],
            },
          },
        },
      },
    },
  },
}

Step 3: Custom Skill Implementation (SKILL.md)

Create an automated GitHub PR review and triage skill in ~/.openclaw/workspace/skills/github-triage/SKILL.md:

---
name: github-triage
description: Inspect pull requests, check CI workflow status, and summarize failed test runs.
user-invocable: true
metadata: {
  "openclaw": {
    "emoji": "πŸ”",
    "requires": { "bins": ["gh", "jq"] }
  }
}
---

Use the GitHub CLI (`gh`) to query repository status, inspect active PRs, and triage CI failures.

## Operational Commands

### 1. Fetch Pending Review Requests
```bash
gh pr list --repo owner/repo --search "review-requested:@me is:open" --json number,title,author,headRefName
```

### 2. Inspect Failed CI Workflows
```bash
gh run list --repo owner/repo --status failure --limit 5 --json name,conclusion,databaseId,headBranch
```

### 3. Retrieve Failure Logs
```bash
gh run view RUN_ID --repo owner/repo --log-failed
```

## Response Constraints
- When reporting CI failures, summarize the specific failing test suite and error traceback concisely.
- Do not approve PRs or trigger deployments without explicit user confirmation.

Verify the newly authored skill:

openclaw skills verify github-triage

Step 4: Event-Driven Automation (Cron & Webhooks)

Configure automated background tasks in ~/.openclaw/openclaw.json:

{
  agents: {
    defaults: {
      cron: {
        "0 8 * * 1-5": {
          message: "Execute daily morning briefing: query calendar events, summarize pending GitHub PRs requiring review, and check system disk space.",
          channel: "telegram",
          sessionKey: "main",
        },
      },
    },
  },
  hooks: {
    entries: [
      {
        id: "github-webhook",
        url: "/webhook/github",
        events: ["pull_request.opened", "workflow_run.completed"],
        auth: { type: "github-webhook-secret", secret: "${WEBHOOK_SECRET}" },
        agent: {
          message: "Incoming GitHub event on {{repository}}: {{action}}. Title: {{title}}.",
          sessionKey: "main",
        },
      },
    ],
  },
}

Security Hardening Checklist

  1. Enforce DM Pairing Policies: Never set dmPolicy: "open" on public channels (Telegram, Discord) without explicit allowFrom user IDs. Unknown users should receive cryptographic pairing codes requiring administrative approval via openclaw pairing approve <id>.
  2. Container Isolation & Capability Dropping: Ensure non-main sessions run inside Docker containers with --cap-drop=ALL and --security-opt=no-new-privileges:true.
  3. Audit Active Skills with Doctor: Regularly execute openclaw doctor to identify unauthenticated webhook endpoints, loose file permissions, or unpinned dependencies.

Troubleshooting Common Gateway Issues

1. WhatsApp Pairing Invalidation

  • Symptom: Gateway logs report Baileys session disconnected: 401 Unauthorized.
  • Remedy: WhatsApp session keys in ~/.openclaw/whatsapp/ expired. Delete the credentials folder and re-run openclaw gateway restart to scan the QR code.

2. Docker Sandbox Socket Permission Denied

  • Symptom: Tool execution fails with EACCES: permission denied, connect /var/run/docker.sock.
  • Remedy: Add the gateway user to the host Docker group: sudo usermod -aG docker $USER and restart the daemon.

3. Skill Metadata Validation Errors

  • Symptom: Custom skill fails to load during startup.
  • Remedy: Validate that the YAML frontmatter in SKILL.md is strictly formatted and that all required binaries in requires.bins exist in $PATH.

Subscribe to Unlock the Rest

This section is exclusive to active subscribers. Support our work and unlock this article immediately.

Unlock this post and get unlimited access to all premium articles.

References

  1. OpenClaw Core Team. (2024–2026). OpenClaw: Self-Hosted Personal AI Agent Platform. GitHub.
  2. Anthropic. (2024). Model Context Protocol (MCP) Specification. modelcontextprotocol.io.
  3. Docker Inc. (2024). Docker Engine Security and Container Isolation Best Practices.
  4. Baileys Project. (2024). TypeScript/JavaScript WhatsApp Web API Library.


Cite this Article

@article{ailinkdeeptech2026openclawselfhostedpersonalaiagentcomplete2026tutorial,
  title={OpenClaw: Architecture, Gateway Routing, Sandboxed MCP Skills, and Multi-Channel Deployment},
  author={AILinkDeepTech},
  journal={AILinkDeepTech AI Research Portal},
  year={2026},
  url={https://ailinkdeeptech.com/articles/openclaw-self-hosted-personal-ai-agent-complete-2026-tutorial}
}

Related Articles