> 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/ch21-channel-extension-mechanism/21.4-developing-custom-extensions.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 21.4 Developing Custom Extensions

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~850k tokens, Output \~80k tokens (Chapter 21 total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In the previous three sections, we understood OpenClaw's extension mechanism from three perspectives: architecture, API, and examples. This section enters the practical phase—providing step-by-step guidance on developing a custom channel extension, enabling readers to independently develop new channels.

***

## 21.4.1 Extension Scaffolding Setup

### Directory Structure

A minimally viable channel extension requires the following files:

```
my-channel/
├── package.json              # npm package configuration
├── openclaw.plugin.json      # Plugin manifest (required)
├── index.ts                  # Entry file
├── tsconfig.json             # TypeScript configuration (optional but recommended)
└── src/
    ├── channel.ts            # ChannelPlugin definition
    ├── monitor.ts            # Message listening logic
    ├── send.ts               # Message sending logic
    └── runtime.ts            # Runtime reference cache
```

### package.json

```json
{
  "name": "openclaw-channel-mychat",
  "version": "0.1.0",
  "type": "module",
  "openclaw": {
    "extensions": ["index.ts"]
  },
  "dependencies": {
    "mychat-sdk": "^1.0.0"
  }
}
```

Key configurations:

| Field                 | Required    | Description                                                        |
| --------------------- | ----------- | ------------------------------------------------------------------ |
| `openclaw.extensions` | ✅           | Declares entry file path array, read by plugin discovery mechanism |
| `type: "module"`      | Recommended | ESM module format                                                  |
| `dependencies`        | As needed   | Third-party SDK dependencies                                       |

### openclaw\.plugin.json

```json
{
  "id": "mychat",
  "channels": ["mychat"],
  "configSchema": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "apiKey": {
        "type": "string",
        "description": "MyChat Bot API Key"
      },
      "webhookPort": {
        "type": "number",
        "description": "Webhook listening port",
        "default": 4000
      }
    },
    "required": ["apiKey"]
  }
}
```

Manifest field descriptions:

| Field          | Purpose                                                                     |
| -------------- | --------------------------------------------------------------------------- |
| `id`           | Globally unique identifier, used for `plugins.entries.mychat` configuration |
| `channels`     | Declares channel IDs provided by this plugin, used for Gateway auto-loading |
| `configSchema` | JSON Schema, validates `plugins.entries.mychat.config` when plugin loads    |

### runtime.ts — Runtime Cache

```typescript
// src/runtime.ts
import type { PluginRuntime } from "openclaw/plugin-sdk";

let runtime: PluginRuntime | null = null;

export function setMyChatRuntime(rt: PluginRuntime) {
  runtime = rt;
}

export function getMyChatRuntime(): PluginRuntime {
  if (!runtime) throw new Error("MyChat runtime not initialized");
  return runtime;
}
```

This pattern appears repeatedly in section 13.3. Since `PluginRuntime` is only injected when `register()` is called, other modules cannot obtain it at import time, so a module-level cache is needed.

### index.ts — Entry File

```typescript
// index.ts
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { emptyPluginConfigSchema } from "openclaw/plugin-sdk";
import { myChatPlugin } from "./src/channel.js";
import { setMyChatRuntime } from "./src/runtime.js";

const plugin = {
  id: "mychat",
  name: "MyChat",
  description: "MyChat channel plugin",
  configSchema: emptyPluginConfigSchema(),
  register(api: OpenClawPluginApi) {
    setMyChatRuntime(api.runtime);
    api.registerChannel({ plugin: myChatPlugin });
  },
};

export default plugin;
```

> **Note**: If your plugin has custom configuration (not empty schema), you can replace `emptyPluginConfigSchema()` with a custom Zod Schema or hand-written `safeParse` function. The implementation of `emptyPluginConfigSchema()` only accepts empty objects or `undefined`.

***

## 21.4.2 Implementing Channel Adapter Interface

### Minimally Viable ChannelPlugin

`ChannelPlugin` has nearly 20 optional adapter slots, but **most are optional**. A minimally viable channel only needs to implement `id`, `meta`, `capabilities`, and `config`:

```typescript
// src/channel.ts
import type { ChannelPlugin, OpenClawConfig } from "openclaw/plugin-sdk";
import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk";

type MyChatAccount = {
  accountId: string;
  enabled: boolean;
  configured: boolean;
};

const meta = {
  id: "mychat",
  label: "MyChat",
  selectionLabel: "MyChat Messenger",
  blurb: "MyChat instant messaging platform",
  order: 100,    // Sorting weight in channel selection list
};

export const myChatPlugin: ChannelPlugin<MyChatAccount> = {
  id: "mychat",
  meta,
  
  // Capability declaration — tell OpenClaw what this channel supports
  capabilities: {
    chatTypes: ["direct", "group"],   // Support DM and group chat
    polls: false,                     // No poll support
    reactions: false,                 // No emoji reaction support
    threads: false,                   // No threading support
    media: true,                      // Support media (images/files)
  },
  
  // Config adapter — account management
  config: {
    listAccountIds: () => [DEFAULT_ACCOUNT_ID],
    
    resolveAccount: (cfg) => ({
      accountId: DEFAULT_ACCOUNT_ID,
      enabled: cfg.channels?.mychat?.enabled !== false,
      configured: Boolean(cfg.channels?.mychat?.apiKey),
    }),
    
    defaultAccountId: () => DEFAULT_ACCOUNT_ID,
    
    isConfigured: (account) => account.configured,
    
    describeAccount: (account) => ({
      accountId: account.accountId,
      enabled: account.enabled,
      configured: account.configured,
    }),
    
    resolveAllowFrom: ({ cfg }) => 
      cfg.channels?.mychat?.allowFrom ?? [],
    
    formatAllowFrom: ({ allowFrom }) =>
      allowFrom.map((entry) => String(entry).trim().toLowerCase()).filter(Boolean),
    
    setAccountEnabled: ({ cfg, enabled }) => ({
      ...cfg,
      channels: {
        ...cfg.channels,
        mychat: { ...cfg.channels?.mychat, enabled },
      },
    }),
    
    deleteAccount: ({ cfg }) => {
      const next = { ...cfg } as OpenClawConfig;
      const nextChannels = { ...cfg.channels };
      delete nextChannels.mychat;
      next.channels = nextChannels;
      return next;
    },
  },
  
  // Gateway adapter — message listening
  gateway: {
    startAccount: async (ctx) => {
      const { startMyChatMonitor } = await import("./monitor.js");
      return startMyChatMonitor({
        cfg: ctx.cfg,
        abortSignal: ctx.abortSignal,
        runtime: ctx.runtime,
        log: ctx.log,
      });
    },
  },
};
```

### Significance of Capability Declaration

`capabilities` is not just metadata; other modules in OpenClaw make decisions based on it:

```typescript
capabilities: {
  chatTypes: ["direct", "group"],  // → Agent tool's target parameter will include group options
  polls: false,                    // → Agent won't generate poll-related tool calls
  threads: false,                  // → Message dispatch won't try to maintain thread context
  media: true,                     // → Agent can send images and files
}
```

### Progressively Expanding Adapters

As functionality improves, you can gradually add more adapters:

**Phase 1 (Minimally Viable)**: `config` + `gateway`

**Phase 2 (Security Control)**: Add `security` + `pairing`

```typescript
security: {
  resolveDmPolicy: ({ account }) => ({
    policy: "pairing",               // New contacts require approval
    allowFrom: account.allowFrom,
    policyPath: "channels.mychat.dm.policy",
    allowFromPath: "channels.mychat.dm.allowFrom",
  }),
},

pairing: {
  idLabel: "myChatUserId",
  normalizeAllowEntry: (entry) => entry.replace(/^mychat:/i, ""),
  notifyApproval: async ({ cfg, id }) => {
    await sendMyChat(cfg, id, "Verified! You can start chatting now.");
  },
},
```

**Phase 3 (Enhanced Message Capabilities)**: Add `outbound` + `messaging` + `actions`

**Phase 4 (Operations Features)**: Add `status` + `directory` + `onboarding`

***

## 21.4.3 Registering with Plugin System

### Installation Methods

There are three ways to register a custom extension with OpenClaw:

#### Method 1: Workspace-Level Installation (Recommended for Development)

Place the extension directory under the project's `.openclaw/extensions/`:

```bash
# Assuming OpenClaw workspace is at ~/openclaw-workspace
mkdir -p ~/openclaw-workspace/.openclaw/extensions
cp -r my-channel ~/openclaw-workspace/.openclaw/extensions/
```

OpenClaw will automatically discover and load it on startup. No configuration needed.

#### Method 2: Global Installation

Place it in the user-level configuration directory:

```bash
cp -r my-channel ~/.config/openclaw/extensions/
```

All workspaces can use this extension.

#### Method 3: Configuration Path Installation

Explicitly specify the path in `openclaw.config.yaml`:

```yaml
plugins:
  loadPaths:
    - /path/to/my-channel
```

Suitable for development pointing to source directory; no need to copy after changes.

### Configuration Enable

Add extension configuration in `openclaw.config.yaml`:

```yaml
plugins:
  entries:
    mychat:
      enabled: true
      config:
        apiKey: "your-api-key-here"
        webhookPort: 4000

channels:
  mychat:
    enabled: true
    allowFrom:
      - "user123"
      - "user456"
```

### Verify Loading

After starting OpenClaw, you can confirm successful plugin loading through Gateway logs:

```
[plugins] loaded mychat (bundled) — 1 channel, 0 tools, 0 hooks
```

If loading fails, diagnostic information appears in logs:

```
[plugins] error: mychat — config validation failed: apiKey is required
```

You can also view the list of loaded plugins through Gateway RPC:

```bash
openclaw status
# Output should include status information for mychat channel
```

***

## 21.4.4 Testing and Debugging

### Unit Tests

Extensions can be tested independently. Vitest is recommended (the test framework used by OpenClaw's official extensions):

```typescript
// src/channel.test.ts
import { describe, it, expect } from "vitest";
import { myChatPlugin } from "./channel.js";

describe("myChatPlugin", () => {
  it("should have correct id and meta", () => {
    expect(myChatPlugin.id).toBe("mychat");
    expect(myChatPlugin.meta.label).toBe("MyChat");
  });
  
  it("should resolve account correctly", () => {
    const cfg = {
      channels: {
        mychat: { enabled: true, apiKey: "test-key" },
      },
    };
    const account = myChatPlugin.config.resolveAccount(cfg as any);
    expect(account.enabled).toBe(true);
    expect(account.configured).toBe(true);
  });
  
  it("should detect unconfigured account", () => {
    const cfg = { channels: {} };
    const account = myChatPlugin.config.resolveAccount(cfg as any);
    expect(account.configured).toBe(false);
  });
});
```

Tests in OpenClaw's official extensions can serve as references—for example, `extensions/msteams/src/` contains multiple test files like `attachments.test.ts`, `inbound.test.ts`, `messenger.test.ts`.

### Integration Tests

For scenarios requiring verification of complete message send/receive pipelines, integration testing can be done by mocking messages:

```typescript
// src/monitor.test.ts
import { describe, it, expect, vi } from "vitest";

describe("monitorMyChatProvider", () => {
  it("should process incoming message", async () => {
    const dispatchMock = vi.fn();
    
    // Simulate receiving a message
    const message = {
      from: "user123",
      text: "Hello",
      timestamp: Date.now(),
    };
    
    await processIncoming(message, { dispatch: dispatchMock });
    
    expect(dispatchMock).toHaveBeenCalledWith(
      expect.objectContaining({
        From: "user123",
        Body: "Hello",
      })
    );
  });
});
```

### Debugging Tips

**1. Enable Verbose Logging**

Enable verbose mode in configuration:

```yaml
logging:
  level: debug
```

Or set environment variable at startup:

```bash
OPENCLAW_LOG_LEVEL=debug openclaw start
```

**2. Use Plugin Runtime's Logger**

```typescript
// In register()
register(api: OpenClawPluginApi) {
  const log = api.logger;
  log.info("MyChat plugin loading...");
  log.debug("Plugin config: " + JSON.stringify(api.pluginConfig));
}

// In other modules via runtime
const runtime = getMyChatRuntime();
const log = runtime.logging.getChildLogger({ name: "mychat" });
log.info("Processing message...");
```

**3. Diagnostic Events**

If you need to monitor extension runtime status, use the diagnostic event system:

```typescript
import { emitDiagnosticEvent, isDiagnosticsEnabled } from "openclaw/plugin-sdk";

if (isDiagnosticsEnabled()) {
  emitDiagnosticEvent({
    type: "webhook_received",
    channel: "mychat",
    timestamp: Date.now(),
    metadata: { messageId: msg.id },
  });
}
```

**4. Message Processing Pipeline Debugging**

For inbound message processing, key debugging checkpoints:

```
Webhook Reception → Allowlist Check → Message Normalization → Agent Routing → Agent Processing → Reply Dispatch → Sending
```

If a message "disappears," the most common causes are:

* Sender not in `allowFrom` list
* Message format doesn't match expectations, normalization fails
* Agent routing didn't match any Agent
* `enabled: false` in configuration

### Publishing to npm

After completing development, you can publish the extension as an npm package:

```bash
# Add necessary fields
npm version patch
npm publish --access public
```

Other users install it:

```bash
npm install -g openclaw-channel-mychat
# Or install in workspace
npm install openclaw-channel-mychat
```

Then add loadPaths in `openclaw.config.yaml` pointing to the installation directory, or symlink it to `~/.config/openclaw/extensions/`.

***

## Summary of This Section

1. **A minimally viable extension requires only 5 files**: `package.json`, `openclaw.plugin.json`, `index.ts`, `src/channel.ts`, `src/runtime.ts`. The `openclaw.plugin.json` manifest and the `register()` function in the entry file are mandatory.
2. **Most of ChannelPlugin's 20 adapter slots are optional**, with progressive development recommended: first implement `config` + `gateway` (minimally viable), then gradually add `security`, `outbound`, `status`, etc.
3. **Three installation methods** suit different scenarios: workspace installation for development/debugging, global installation for personal use, configuration path installation for source code development.
4. **Testing should be in two layers**: unit tests verify each ChannelPlugin adapter implementation, integration tests verify complete message send/receive pipelines.
5. **The core of debugging is logging and diagnostic events**: through three levels of logging—`api.logger`, `runtime.logging.getChildLogger()`, and `emitDiagnosticEvent()`—you can locate any problem in the message processing pipeline.

***

> ### 🔬 Going Deeper: 21.5 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**21.5 Source Deep Dive: The Loader, jiti, and the SDK Surface**](https://www.openclawbook.xyz/en/ch21-channel-extension-mechanism/21.5-source-deep-dive-loader-jiti-and-sdk-surface.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
