> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch42-hands-on-project/42.2-core-feature-implementation.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 42.2 Core Feature Implementation

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~355k tokens, Output \~6k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

This section implements the core skeleton of MiniClaw: WebSocket Gateway, message routing, Agent execution loop, and basic tool system.

## 42.2.1 Building the WebSocket Gateway Skeleton

The Gateway is the central hub of MiniClaw, responsible for accepting client connections and routing messages.

### Minimal RPC Protocol

Referencing OpenClaw's frame protocol (Chapter 11), define a simplified version:

```typescript
// src/gateway/protocol.ts

export type RpcRequest = {
  type: "req";
  id: string;       // Request ID
  method: string;    // Method name
  params?: unknown;  // Parameters
};

export type RpcResponse = {
  type: "res";
  id: string;       // Corresponding request ID
  result?: unknown;  // Success result
  error?: string;    // Error message
};

export type RpcEvent = {
  type: "event";
  event: string;     // Event name
  payload?: unknown;  // Event data
};

export type RpcFrame = RpcRequest | RpcResponse | RpcEvent;
```

### WebSocket Server

```typescript
// src/gateway/server.ts

import { WebSocketServer, WebSocket } from "ws";
import { randomUUID } from "node:crypto";
import type { RpcFrame, RpcRequest, RpcResponse } from "./protocol.js";

type ClientConnection = {
  id: string;
  ws: WebSocket;
  subscribedEvents: Set<string>;
};

export class Gateway {
  private wss: WebSocketServer;
  private clients = new Map<string, ClientConnection>();
  private handlers = new Map<string, (params: unknown) => Promise<unknown>>();

  constructor(port: number) {
    this.wss = new WebSocketServer({ port });
    this.wss.on("connection", (ws) => this.handleConnection(ws));
  }

  // Register RPC method handler
  registerMethod(method: string, handler: (params: unknown) => Promise<unknown>) {
    this.handlers.set(method, handler);
  }

  // Broadcast event to all subscribers
  broadcast(event: string, payload?: unknown) {
    const frame: RpcFrame = { type: "event", event, payload };
    const data = JSON.stringify(frame);
    for (const client of this.clients.values()) {
      if (client.subscribedEvents.has(event) || client.subscribedEvents.has("*")) {
        client.ws.send(data);
      }
    }
  }

  private handleConnection(ws: WebSocket) {
    const clientId = randomUUID();
    const client: ClientConnection = {
      id: clientId,
      ws,
      subscribedEvents: new Set(["*"]),  // Subscribe to all events by default
    };
    this.clients.set(clientId, client);

    ws.on("message", async (raw) => {
      try {
        const frame = JSON.parse(raw.toString()) as RpcFrame;
        if (frame.type === "req") {
          await this.handleRequest(client, frame);
        }
      } catch (err) {
        console.error("Frame parse error:", err);
      }
    });

    ws.on("close", () => {
      this.clients.delete(clientId);
    });
  }

  private async handleRequest(client: ClientConnection, req: RpcRequest) {
    const handler = this.handlers.get(req.method);
    const res: RpcResponse = { type: "res", id: req.id };
    if (!handler) {
      res.error = `Unknown method: ${req.method}`;
    } else {
      try {
        res.result = await handler(req.params);
      } catch (err) {
        res.error = err instanceof Error ? err.message : String(err);
      }
    }
    client.ws.send(JSON.stringify(res));
  }
}
```

This Gateway implementation realizes the core of OpenClaw's three-frame protocol: request-response + event broadcasting.

## 42.2.2 Implementing Message Routing and Session Management

### Session Storage

```typescript
// src/gateway/session-store.ts

export type Session = {
  key: string;
  messages: Array<{
    role: "user" | "assistant" | "system";
    content: string;
  }>;
  model: string;
  createdAt: number;
  updatedAt: number;
};

export class SessionStore {
  private sessions = new Map<string, Session>();

  getOrCreate(key: string, model: string): Session {
    let session = this.sessions.get(key);
    if (!session) {
      session = {
        key,
        messages: [],
        model,
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };
      this.sessions.set(key, session);
    }
    return session;
  }

  addMessage(key: string, role: "user" | "assistant", content: string) {
    const session = this.sessions.get(key);
    if (!session) return;
    session.messages.push({ role, content });
    session.updatedAt = Date.now();
  }

  getMessages(key: string) {
    return this.sessions.get(key)?.messages ?? [];
  }

  reset(key: string) {
    this.sessions.delete(key);
  }
}
```

### Route Registration

Register core RPC methods on the Gateway:

```typescript
// src/gateway/routes.ts

export function registerRoutes(
  gateway: Gateway,
  sessions: SessionStore,
  agent: AgentRunner,
) {
  // Send message to Agent
  gateway.registerMethod("chat.send", async (params) => {
    const { sessionKey, message } = params as {
      sessionKey: string;
      message: string;
    };
    const session = sessions.getOrCreate(sessionKey, "claude-sonnet-4-20250514");
    sessions.addMessage(sessionKey, "user", message);

    // Asynchronously execute Agent execution loop
    const reply = await agent.run({
      sessionKey,
      messages: sessions.getMessages(sessionKey),
    });

    sessions.addMessage(sessionKey, "assistant", reply);

    // Broadcast chat event
    gateway.broadcast("chat", {
      sessionKey,
      state: "final",
      message: { role: "assistant", content: reply },
    });

    return { ok: true };
  });

  // Session management
  gateway.registerMethod("sessions.list", async () => {
    // Return session list
  });

  gateway.registerMethod("sessions.reset", async (params) => {
    const { key } = params as { key: string };
    sessions.reset(key);
    return { ok: true };
  });
}
```

## 42.2.3 Integrating with LLM APIs

### Anthropic Adapter

```typescript
// src/providers/anthropic.ts

import Anthropic from "@anthropic-ai/sdk";

export type ToolDefinition = {
  name: string;
  description: string;
  input_schema: Record<string, unknown>;
};

export type Message = {
  role: "user" | "assistant";
  content: string | Array<{ type: string; [key: string]: unknown }>;
};

export class AnthropicProvider {
  private client: Anthropic;

  constructor(apiKey: string) {
    this.client = new Anthropic({ apiKey });
  }

  async chat(params: {
    model: string;
    messages: Message[];
    tools?: ToolDefinition[];
    system?: string;
    maxTokens?: number;
  }) {
    const response = await this.client.messages.create({
      model: params.model,
      max_tokens: params.maxTokens ?? 4096,
      system: params.system,
      messages: params.messages,
      tools: params.tools,
    });
    return response;
  }
}
```

### Agent Execution Loop

Referencing OpenClaw's `pi-embedded-runner/` (Chapter 15), implement the core tool invocation loop:

```typescript
// src/agent/runner.ts

export class AgentRunner {
  private provider: AnthropicProvider;
  private tools: Map<string, ToolExecutor>;
  private systemPrompt: string;

  constructor(params: {
    provider: AnthropicProvider;
    tools: ToolExecutor[];
    systemPrompt: string;
  }) {
    this.provider = params.provider;
    this.tools = new Map(params.tools.map(t => [t.name, t]));
    this.systemPrompt = params.systemPrompt;
  }

  async run(params: {
    sessionKey: string;
    messages: Message[];
  }): Promise<string> {
    const toolDefs = Array.from(this.tools.values()).map(t => t.definition);
    let messages = [...params.messages];
    const MAX_TURNS = 10;  // Maximum tool invocation rounds

    for (let turn = 0; turn < MAX_TURNS; turn++) {
      const response = await this.provider.chat({
        model: "claude-sonnet-4-20250514",
        messages,
        tools: toolDefs,
        system: this.systemPrompt,
      });

      // Check for tool invocations
      const toolUseBlocks = response.content.filter(
        (block) => block.type === "tool_use"
      );

      if (toolUseBlocks.length === 0) {
        // No tool invocation → extract text reply
        const textBlock = response.content.find(
          (block) => block.type === "text"
        );
        return textBlock?.text ?? "";
      }

      // Tool invocation found → execute and continue loop
      messages.push({
        role: "assistant",
        content: response.content,
      });

      const toolResults = [];
      for (const toolUse of toolUseBlocks) {
        const executor = this.tools.get(toolUse.name);
        let result: string;
        try {
          result = await executor.execute(toolUse.input);
        } catch (err) {
          result = `Error: ${err.message}`;
        }
        toolResults.push({
          type: "tool_result",
          tool_use_id: toolUse.id,
          content: result,
        });
      }

      messages.push({
        role: "user",
        content: toolResults,
      });
    }

    return "(Reached maximum tool invocation rounds limit)";
  }
}
```

This loop implements the core logic of OpenClaw's Agent runtime: send message → check for tool invocations → execute tools → feed results back to LLM → repeat. `MAX_TURNS = 10` is a safety valve to prevent infinite loops.

## 42.2.4 Implementing Basic Tool System

### Tool Interface

```typescript
// src/agent/tools/types.ts

export type ToolExecutor = {
  name: string;
  definition: ToolDefinition;
  execute: (input: Record<string, unknown>) => Promise<string>;
};
```

### Bash Tool

```typescript
// src/agent/tools/bash.ts

import { execSync } from "node:child_process";

export const bashTool: ToolExecutor = {
  name: "bash",
  definition: {
    name: "bash",
    description: "Execute a bash command and return the output.",
    input_schema: {
      type: "object",
      properties: {
        command: { type: "string", description: "The command to execute" },
      },
      required: ["command"],
    },
  },
  execute: async (input) => {
    const command = input.command as string;
    // Safety check: block dangerous commands
    const BLOCKED = ["rm -rf /", "mkfs", "dd if=/dev"];
    if (BLOCKED.some(b => command.includes(b))) {
      return "Error: This command is blocked for safety.";
    }
    try {
      const output = execSync(command, {
        timeout: 30_000,  // 30 second timeout
        maxBuffer: 1024 * 1024,  // 1MB output limit
        encoding: "utf-8",
      });
      return output.slice(0, 10_000);  // Truncate long output
    } catch (err) {
      return `Error: ${err.message}`;
    }
  },
};
```

### File Read Tool

```typescript
// src/agent/tools/read.ts

import fs from "node:fs";
import path from "node:path";

export const readTool: ToolExecutor = {
  name: "read",
  definition: {
    name: "read",
    description: "Read the contents of a file.",
    input_schema: {
      type: "object",
      properties: {
        filePath: { type: "string", description: "Absolute file path" },
      },
      required: ["filePath"],
    },
  },
  execute: async (input) => {
    const filePath = input.filePath as string;
    // Security: restrict to workspace directory
    const resolved = path.resolve(filePath);
    if (!resolved.startsWith(process.cwd())) {
      return "Error: Access denied. File outside workspace.";
    }
    try {
      return fs.readFileSync(resolved, "utf-8").slice(0, 50_000);
    } catch (err) {
      return `Error: ${err.message}`;
    }
  },
};
```

### Entry Point

Assemble all components together:

```typescript
// src/index.ts

import { Gateway } from "./gateway/server.js";
import { SessionStore } from "./gateway/session-store.js";
import { AgentRunner } from "./agent/runner.js";
import { AnthropicProvider } from "./providers/anthropic.js";
import { bashTool } from "./agent/tools/bash.js";
import { readTool } from "./agent/tools/read.js";
import { registerRoutes } from "./gateway/routes.js";

const provider = new AnthropicProvider(process.env.ANTHROPIC_API_KEY!);
const agent = new AgentRunner({
  provider,
  tools: [bashTool, readTool],
  systemPrompt: "You are a helpful AI assistant. You can execute commands and read files to help users.",
});

const sessions = new SessionStore();
const gateway = new Gateway(3000);
registerRoutes(gateway, sessions, agent);

console.log("MiniClaw Gateway running on ws://localhost:3000");
```

***

## Summary of This Section

1. **Gateway** implements a simplified version of OpenClaw's three-frame protocol (req/res/event), supporting RPC method registration and event broadcasting.
2. **Session storage** uses an in-memory Map, providing basic operations like create/read/reset.
3. **LLM adapter** encapsulates the Anthropic SDK, unifying the API interface.
4. **Agent execution loop** implements the core "call LLM → check for tool invocations → execute tools → feed results back" cycle, with a maximum of 10 rounds.
5. **Tool system** is defined with a unified interface; the Bash tool includes timeout (30s) and dangerous command blocking, while the file read tool is restricted to the workspace directory.
