Guide · Chime SDK Messaging · Channels, ChannelFlow & Message Types

AWS Chime SDK Messaging for MCP Servers — Channels, ChannelFlow, and Message Patterns

Chime SDK Messaging provides persistent, real-time channels backed by an AppInstance namespace, with two orthogonal design axes: channel mode (UNRESTRICTED vs RESTRICTED) controlling who can send, and channel privacy (PUBLIC vs PRIVATE) controlling who can discover and join. MCP server tools built on @aws-sdk/client-chime-sdk-messaging can create channels, add members, send STANDARD (persisted) or CONTROL (ephemeral signaling) messages, attach ChannelFlow processors that invoke Lambda functions to moderate or enrich every message in flight, and permanently ban users. The first-hour failure is treating the ChimeBearer parameter as optional — it is mandatory in every Messaging API call and must be an AppInstanceUser ARN, not an IAM ARN.

TL;DR

Channels have two independent modes: Mode (UNRESTRICTED = anyone in channel can send; RESTRICTED = only moderators can send) and Privacy (PUBLIC = discoverable; PRIVATE = membership-only). SendChannelMessage takes a Type of STANDARD (stored, appears in ListChannelMessages) or CONTROL (real-time only, never persisted — use for signaling like "user is typing"). ChannelFlow attaches Lambda processors to a channel; every STANDARD message passes through the processor before delivery — use for content moderation, enrichment, or routing. Membership types are DEFAULT, HIDDEN (member but invisible to others), and GUEST (no message send rights). CreateChannelBan permanently blocks an AppInstanceUser from a specific channel; DeleteChannelMembership removes them without banning. All calls require ChimeBearer: appInstanceUserArn.

Channel creation and modes

A channel is the fundamental unit of Chime SDK Messaging. Channels are persistent objects that survive connection drops — messages sent while a user is offline are retrieved when they reconnect via ListChannelMessages. Channels belong to exactly one AppInstance and cannot be moved between AppInstances.

Two properties control channel behavior at creation time and cannot be changed afterward without deleting and recreating the channel:

import {
  CreateChannelCommand,
  DeleteChannelCommand,
  DescribeChannelCommand,
  ListChannelsCommand,
} from '@aws-sdk/client-chime-sdk-messaging';

server.tool(
  'create_channel',
  'Create a new Chime SDK Messaging channel',
  {
    name: z.string().max(256).describe('Channel display name'),
    mode: z.enum(['UNRESTRICTED', 'RESTRICTED']).default('UNRESTRICTED'),
    privacy: z.enum(['PUBLIC', 'PRIVATE']).default('PUBLIC'),
    metadata: z.string().optional().describe('Arbitrary string metadata (max 1 KB)'),
  },
  async ({ name, mode, privacy, metadata }) => {
    const result = await messagingClient.send(
      new CreateChannelCommand({
        AppInstanceArn: APP_INSTANCE_ARN,
        Name: name,
        Mode: mode,
        Privacy: privacy,
        Metadata: metadata,
        ChimeBearer: SERVICE_USER_ARN,
        // ClientRequestToken ensures idempotency — reuse the same token to avoid duplicate channels
        ClientRequestToken: `channel-${name.toLowerCase().replace(/\s+/g, '-')}-v1`,
      })
    );
    return { content: [{ type: 'text', text: JSON.stringify({ channelArn: result.ChannelArn }) }] };
  }
);

The ClientRequestToken provides at-most-once channel creation. If you call CreateChannel twice with the same token, the second call returns the existing channel ARN rather than creating a duplicate. Use a stable token derived from the channel's logical name rather than a random UUID so that retries after transient failures are safe.

Channel membership types

When adding users to a channel via CreateChannelMembership, the Type parameter controls the member's visibility and capabilities within the channel. This is a distinct concept from channel Mode — mode controls who can send; membership type controls how the member appears to others.

TypeVisible to other members?Can send?Use case
DEFAULT Yes Depends on channel Mode Standard chat participant
HIDDEN No — invisible to non-admins Depends on channel Mode Monitoring bots, AI observers, compliance recorders
GUEST Yes No — receive only Read-only participants (customers viewing support chat without replying)
import {
  CreateChannelMembershipCommand,
  DeleteChannelMembershipCommand,
  ListChannelMembershipsCommand,
} from '@aws-sdk/client-chime-sdk-messaging';

server.tool(
  'add_channel_member',
  'Add an AppInstanceUser to a Chime channel',
  {
    channelArn: z.string().describe('Channel ARN'),
    memberArn: z.string().describe('AppInstanceUser ARN to add'),
    memberType: z.enum(['DEFAULT', 'HIDDEN', 'GUEST']).default('DEFAULT'),
  },
  async ({ channelArn, memberArn, memberType }) => {
    await messagingClient.send(
      new CreateChannelMembershipCommand({
        ChannelArn: channelArn,
        MemberArn: memberArn,
        Type: memberType,
        ChimeBearer: SERVICE_USER_ARN,
      })
    );
    return { content: [{ type: 'text', text: `Added ${memberArn} as ${memberType}` }] };
  }
);

MCP server tools that observe channel activity without participating should be added as HIDDEN members. The service bot joining as DEFAULT is visible in member lists — a user opening the channel member list would see "MCP Service Bot" as a participant, which can be confusing in customer-facing channels.

Sending messages: STANDARD vs CONTROL

Chime SDK Messaging has two fundamentally different message types. The distinction matters for MCP server tools: they serve different communication patterns and are stored differently.

STANDARD messages are persistent. They are stored in Chime's message history, appear in ListChannelMessages results, and trigger push notifications. Use STANDARD for all messages that form part of the conversation record — user responses, AI-generated answers, support tickets, structured data payloads.

CONTROL messages are ephemeral signaling. They are delivered in real time via WebSocket to connected clients but are never persisted and never appear in ListChannelMessages. Use CONTROL for transient signals: "user is typing" indicators, "stream started" push events, presence pings, and coordination messages that have no meaning outside the current session. CONTROL messages do not pass through ChannelFlow processors and do not count against message rate limits in the same way.

import { SendChannelMessageCommand } from '@aws-sdk/client-chime-sdk-messaging';

// STANDARD: persisted, appears in history, triggers push notifications
server.tool(
  'send_message',
  'Send a persistent STANDARD message to a channel',
  {
    channelArn: z.string(),
    content: z.string().max(4096),
    metadata: z.string().optional().describe('Structured JSON metadata attached to the message'),
    actingUserArn: z.string().optional(),
  },
  async ({ channelArn, content, metadata, actingUserArn }) => {
    const result = await messagingClient.send(
      new SendChannelMessageCommand({
        ChannelArn: channelArn,
        Content: content,
        Type: 'STANDARD',
        Persistence: 'PERSISTENT',
        Metadata: metadata,
        ChimeBearer: actingUserArn ?? SERVICE_USER_ARN,
        ClientRequestToken: `msg-${Date.now()}-${Math.random().toString(36).slice(2)}`,
      })
    );
    return { content: [{ type: 'text', text: JSON.stringify({ messageId: result.MessageId }) }] };
  }
);

// CONTROL: ephemeral signaling, never persisted
server.tool(
  'send_control_signal',
  'Send an ephemeral CONTROL message for real-time signaling',
  {
    channelArn: z.string(),
    signal: z.string().describe('Signal type or payload'),
    actingUserArn: z.string().optional(),
  },
  async ({ channelArn, signal, actingUserArn }) => {
    await messagingClient.send(
      new SendChannelMessageCommand({
        ChannelArn: channelArn,
        Content: signal,
        Type: 'CONTROL',
        Persistence: 'NON_PERSISTENT', // CONTROL messages are always NON_PERSISTENT
        ChimeBearer: actingUserArn ?? SERVICE_USER_ARN,
        ClientRequestToken: `ctrl-${Date.now()}`,
      })
    );
    return { content: [{ type: 'text', text: 'Signal sent' }] };
  }
);

The Metadata field on STANDARD messages is a free-form string up to 1024 characters. It is returned alongside the message content in ListChannelMessages and GetChannelMessage without additional API calls. Use it to attach structured data (message type tag, source system, AI model identifier) without encoding it into the visible message content.

Listing and paginating channel messages

Retrieving channel history requires pagination. ListChannelMessages returns at most 50 messages per call in reverse chronological order by default. The API supports time-range filtering and sort order control, making it suitable for retrieving recent messages, replaying history, or searching a time window.

import { ListChannelMessagesCommand } from '@aws-sdk/client-chime-sdk-messaging';

server.tool(
  'list_channel_messages',
  'Retrieve message history from a Chime channel',
  {
    channelArn: z.string(),
    maxResults: z.number().int().min(1).max(50).default(25),
    notBefore: z.string().optional().describe('ISO 8601 start time (messages after this time)'),
    notAfter: z.string().optional().describe('ISO 8601 end time (messages before this time)'),
    sortOrder: z.enum(['ASCENDING', 'DESCENDING']).default('DESCENDING'),
  },
  async ({ channelArn, maxResults, notBefore, notAfter, sortOrder }) => {
    const messages = [];
    let nextToken: string | undefined;

    do {
      const response = await messagingClient.send(
        new ListChannelMessagesCommand({
          ChannelArn: channelArn,
          MaxResults: maxResults,
          NextToken: nextToken,
          NotBefore: notBefore ? new Date(notBefore) : undefined,
          NotAfter: notAfter ? new Date(notAfter) : undefined,
          SortOrder: sortOrder,
          ChimeBearer: SERVICE_USER_ARN,
        })
      );
      messages.push(...(response.ChannelMessages ?? []));
      nextToken = response.NextToken;
      // Respect maxResults as a per-page limit, not total
    } while (nextToken && messages.length < maxResults * 3);

    const simplified = messages.map(m => ({
      messageId: m.MessageId,
      sender: m.Sender?.Arn,
      content: m.Content,
      metadata: m.Metadata,
      createdTimestamp: m.CreatedTimestamp?.toISOString(),
      type: m.Type,
    }));

    return { content: [{ type: 'text', text: JSON.stringify(simplified, null, 2) }] };
  }
);

When SortOrder is DESCENDING (default), the first page contains the most recent messages. When set to ASCENDING, the first page contains the oldest messages from the specified time range. For MCP tools that feed channel history to an AI context window, ASCENDING with a NotBefore of "24 hours ago" gives chronological order suitable for LLM summarization.

CONTROL messages never appear in ListChannelMessages — only STANDARD (PERSISTENT) messages are returned. If your tool tracks signaling events, you must maintain that state in an external store; Chime does not provide a history API for CONTROL messages.

ChannelFlow: message processing with Lambda

ChannelFlow is a Chime SDK Messaging feature that intercepts every STANDARD message sent to a channel before it is delivered to members. The flow invokes one or more Lambda processor functions that can inspect the message, modify its content or metadata, halt delivery entirely (denying the message), or allow it through unchanged.

ChannelFlows are associated with channels at the AppInstance level, not per-channel — you create a ChannelFlow once and then associate it with one or more channels. The flow can be reused across multiple channels.

import {
  CreateChannelFlowCommand,
  AssociateChannelFlowCommand,
  DisassociateChannelFlowCommand,
} from '@aws-sdk/client-chime-sdk-messaging';

// Create a ChannelFlow with a Lambda processor
const channelFlowResponse = await messagingClient.send(
  new CreateChannelFlowCommand({
    AppInstanceArn: APP_INSTANCE_ARN,
    Name: 'content-moderation-flow',
    ClientRequestToken: 'cf-moderation-v1',
    Processors: [
      {
        Name: 'ModerationLambda',
        Configuration: {
          Lambda: {
            ResourceArn: 'arn:aws:lambda:us-east-1:123456789012:function:chime-moderator',
            InvocationType: 'ASYNC',
          },
        },
        ExecutionOrder: 1,
        FallbackAction: 'CONTINUE', // CONTINUE = allow message if Lambda fails; ABORT = deny
      },
    ],
  })
);

// Associate with a channel
await messagingClient.send(
  new AssociateChannelFlowCommand({
    ChannelArn: channelArn,
    ChannelFlowArn: channelFlowResponse.ChannelFlowArn!,
    ChimeBearer: SERVICE_USER_ARN,
  })
);

The Lambda function receives the message event, can call back to Chime SDK Messaging to update the message content (using the ChannelMessageCallback API within the Lambda), and returns a status indicating whether the message should be allowed or denied. The Lambda has up to 20 seconds to respond before the FallbackAction is applied.

The InvocationType can be ASYNC (Lambda is called but Chime does not wait for the response — the message is delivered immediately after invocation) or SYNC (Chime waits up to 20 seconds for the Lambda response before delivering). Use SYNC for content moderation where you need to block messages; use ASYNC for enrichment tasks like tagging or analytics where delivery should not be delayed.

Set FallbackAction: 'CONTINUE' for enrichment flows — if the Lambda function is throttled or throws an error, messages still deliver normally. Set FallbackAction: 'ABORT' for hard-block moderation where a Lambda failure should prevent message delivery rather than silently bypass moderation. Only use ABORT if the Lambda has high availability; a cold-start surge can inadvertently block all channel messages.

Banning users from channels

Chime SDK Messaging distinguishes between removing a user from a channel and banning them. DeleteChannelMembership removes the user but allows them to rejoin (or be re-added) later. CreateChannelBan creates a permanent block: the banned user cannot join or be added to the channel until the ban is lifted via DeleteChannelBan.

import {
  CreateChannelBanCommand,
  DeleteChannelBanCommand,
  DeleteChannelMembershipCommand,
  ListChannelBansCommand,
} from '@aws-sdk/client-chime-sdk-messaging';

server.tool(
  'ban_channel_member',
  'Permanently ban an AppInstanceUser from a Chime channel',
  {
    channelArn: z.string(),
    userArn: z.string().describe('AppInstanceUser ARN to ban'),
  },
  async ({ channelArn, userArn }) => {
    // Remove membership first (ban alone does not remove an existing member)
    try {
      await messagingClient.send(
        new DeleteChannelMembershipCommand({
          ChannelArn: channelArn,
          MemberArn: userArn,
          ChimeBearer: SERVICE_USER_ARN,
        })
      );
    } catch (err: any) {
      // Ignore NotFoundException if user was not a member
      if (err.name !== 'NotFoundException') throw err;
    }

    // Create the ban
    await messagingClient.send(
      new CreateChannelBanCommand({
        ChannelArn: channelArn,
        MemberArn: userArn,
        ChimeBearer: SERVICE_USER_ARN,
      })
    );

    return { content: [{ type: 'text', text: `User ${userArn} banned from channel` }] };
  }
);

server.tool(
  'unban_channel_member',
  'Remove a ban and allow the user to rejoin the channel',
  {
    channelArn: z.string(),
    userArn: z.string(),
  },
  async ({ channelArn, userArn }) => {
    await messagingClient.send(
      new DeleteChannelBanCommand({
        ChannelArn: channelArn,
        MemberArn: userArn,
        ChimeBearer: SERVICE_USER_ARN,
      })
    );
    return { content: [{ type: 'text', text: `Ban lifted for ${userArn}` }] };
  }
);

Banning does not automatically remove the user's historical messages from the channel — it only blocks future access. If your moderation policy requires message deletion, you must separately call DeleteChannelMessage for each message by that user. The service user acting as AppInstanceAdmin can delete any message regardless of sender, using the message ID returned when the message was originally sent or retrieved from ListChannelMessages.

Channel elasticity search and listing

Chime SDK Messaging provides two listing patterns: ListChannels returns channels associated with the AppInstance that the acting user has access to, and ListChannelsAssociatedWithChannelFlow returns channels using a specific ChannelFlow. For PUBLIC channels, the service user can enumerate all channels without being a member; for PRIVATE channels, only AppInstanceAdmins see channels they have not joined.

import { ListChannelsCommand } from '@aws-sdk/client-chime-sdk-messaging';

server.tool(
  'list_channels',
  'List Chime channels visible to the service user',
  {
    maxResults: z.number().int().min(1).max(50).default(20),
    privacy: z.enum(['PUBLIC', 'PRIVATE']).optional(),
  },
  async ({ maxResults, privacy }) => {
    const channels = [];
    let nextToken: string | undefined;

    do {
      const response = await messagingClient.send(
        new ListChannelsCommand({
          AppInstanceArn: APP_INSTANCE_ARN,
          Privacy: privacy,
          MaxResults: maxResults,
          NextToken: nextToken,
          ChimeBearer: SERVICE_USER_ARN,
        })
      );
      channels.push(...(response.Channels ?? []));
      nextToken = response.NextToken;
    } while (nextToken && channels.length < 200);

    return {
      content: [{
        type: 'text',
        text: JSON.stringify(
          channels.map(c => ({ arn: c.ChannelSummary?.ChannelArn, name: c.ChannelSummary?.Name, mode: c.ChannelSummary?.Mode })),
          null, 2
        ),
      }],
    };
  }
);

Full 5-tool MCP server implementation

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import { ChimeSDKMessagingClient,
  CreateChannelCommand, SendChannelMessageCommand,
  ListChannelMessagesCommand, CreateChannelMembershipCommand,
  CreateChannelBanCommand, DeleteChannelMembershipCommand,
  DeleteChannelBanCommand } from '@aws-sdk/client-chime-sdk-messaging';

const messagingClient = new ChimeSDKMessagingClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const APP_INSTANCE_ARN = process.env.CHIME_APP_INSTANCE_ARN!;
const SERVICE_USER_ARN = process.env.CHIME_SERVICE_USER_ARN!;

const server = new McpServer({ name: 'chime-messaging', version: '1.0.0' });

server.tool('create_channel', 'Create a Chime channel',
  { name: z.string(), mode: z.enum(['UNRESTRICTED','RESTRICTED']).default('UNRESTRICTED'), privacy: z.enum(['PUBLIC','PRIVATE']).default('PUBLIC') },
  async ({ name, mode, privacy }) => {
    const r = await messagingClient.send(new CreateChannelCommand({
      AppInstanceArn: APP_INSTANCE_ARN, Name: name, Mode: mode, Privacy: privacy,
      ChimeBearer: SERVICE_USER_ARN, ClientRequestToken: `ch-${name}`,
    }));
    return { content: [{ type: 'text', text: r.ChannelArn! }] };
  });

server.tool('send_message', 'Send a message to a channel',
  { channelArn: z.string(), content: z.string(), type: z.enum(['STANDARD','CONTROL']).default('STANDARD') },
  async ({ channelArn, content, type }) => {
    const r = await messagingClient.send(new SendChannelMessageCommand({
      ChannelArn: channelArn, Content: content, Type: type,
      Persistence: type === 'STANDARD' ? 'PERSISTENT' : 'NON_PERSISTENT',
      ChimeBearer: SERVICE_USER_ARN, ClientRequestToken: `m-${Date.now()}`,
    }));
    return { content: [{ type: 'text', text: r.MessageId! }] };
  });

server.tool('list_messages', 'List recent messages from a channel',
  { channelArn: z.string(), maxResults: z.number().int().default(20) },
  async ({ channelArn, maxResults }) => {
    const r = await messagingClient.send(new ListChannelMessagesCommand({
      ChannelArn: channelArn, MaxResults: maxResults,
      SortOrder: 'DESCENDING', ChimeBearer: SERVICE_USER_ARN,
    }));
    return { content: [{ type: 'text', text: JSON.stringify(r.ChannelMessages) }] };
  });

server.tool('add_member', 'Add a member to a channel',
  { channelArn: z.string(), memberArn: z.string(), memberType: z.enum(['DEFAULT','HIDDEN','GUEST']).default('DEFAULT') },
  async ({ channelArn, memberArn, memberType }) => {
    await messagingClient.send(new CreateChannelMembershipCommand({
      ChannelArn: channelArn, MemberArn: memberArn, Type: memberType,
      ChimeBearer: SERVICE_USER_ARN,
    }));
    return { content: [{ type: 'text', text: `Added ${memberArn}` }] };
  });

server.tool('ban_user', 'Ban a user from a channel',
  { channelArn: z.string(), userArn: z.string() },
  async ({ channelArn, userArn }) => {
    try { await messagingClient.send(new DeleteChannelMembershipCommand({ ChannelArn: channelArn, MemberArn: userArn, ChimeBearer: SERVICE_USER_ARN })); }
    catch (e: any) { if (e.name !== 'NotFoundException') throw e; }
    await messagingClient.send(new CreateChannelBanCommand({ ChannelArn: channelArn, MemberArn: userArn, ChimeBearer: SERVICE_USER_ARN }));
    return { content: [{ type: 'text', text: `Banned ${userArn}` }] };
  });

const transport = new StdioServerTransport();
await server.connect(transport);

Production gotchas

GotchaSymptomFix
CONTROL message passed to ChannelFlow CONTROL messages bypass ChannelFlow — flow Lambda is never invoked CONTROL messages do not go through ChannelFlow processors; use STANDARD for any message requiring moderation
CONTROL with PERSISTENT persistence BadRequestException CONTROL messages must use Persistence: 'NON_PERSISTENT' — combining CONTROL + PERSISTENT is invalid
Banning without removing membership first Banned user is still a member and can read (but not send) messages Call DeleteChannelMembership before CreateChannelBan to both remove and ban atomically
ChannelFlow FallbackAction: ABORT with cold Lambda All channel messages silently blocked during Lambda cold start Use FallbackAction: 'CONTINUE' for flows where Lambda failure should not block delivery; reserve ABORT only for hard moderation requirements with warm Lambda
Message content limit exceeded BadRequestException when sending long AI-generated content Chime SDK message content is limited to 4096 bytes — truncate or use message metadata to link to externally stored content
ListChannelMessages returning no results for a new channel Empty messages array even though messages were sent CONTROL messages never appear — verify messages were sent with Type: 'STANDARD'; also check SortOrder and time range filters
NotFoundException when calling ListChannels with wrong ChimeBearer Service user does not appear to have access to its own AppInstance Confirm the AppInstance ARN in APP_INSTANCE_ARN matches the region of the Messaging client; a region mismatch causes NotFoundException on the AppInstance, not an auth error

Related pages