Channels Overview
Channels are the transport layer in cmd-ipc. They abstract away the underlying communication mechanism, allowing you to use the same command API regardless of whether you’re talking to a Web Worker, an HTTP server, or any other target.
What is a Channel?
Section titled “What is a Channel?”A channel is a bidirectional communication pipe that:
- Has a unique ID for identification
- Sends and receives messages
- Emits events when messages arrive or the connection closes
- Can operate in client or server mode (depending on the channel type)
Built-in Channels
Section titled “Built-in Channels”cmd-ipc includes three built-in channel implementations:
MessagePortChannel For Web Workers, Node.js worker_threads, and MessageChannel communication.
HTTPChannel For HTTP-based communication with REST APIs and edge functions using NDJSON streaming.
MCPChannel For Model Context Protocol (MCP) integration, exposing commands as AI agent tools.
Channel Interface
Section titled “Channel Interface”All channels implement the ICommandChannel interface. You can create custom channels for any transport (WebSocket, gRPC, etc.) by implementing this interface:
interface ICommandChannel { readonly id: string start(): Promise<void> close(): Promise<void> sendMessage(message: unknown): void on(event: 'message', listener: (message: unknown) => void): void on(event: 'close', listener: () => void): void}| Method | Description |
|---|---|
id | Unique identifier for this channel |
start() | Initialize the channel (called automatically by registry) |
close() | Close the channel and clean up resources |
sendMessage() | Send a message through the channel |
on('message') | Subscribe to incoming messages |
on('close') | Subscribe to channel close events |
Registering Channels
Section titled “Registering Channels”Channels are registered with the CommandRegistry:
const channel = new MessagePortChannel('worker', workerPort)await registry.registerChannel(channel)When a channel is registered:
- The channel’s
start()method is called - For client-mode channels, remote commands are discovered
- The registry begins routing commands to/from the channel