Guide · Amazon IVS Chat · Rooms, Tokens & Moderation API
Amazon IVS Chat for MCP Servers — Chat Rooms, Server-Side Events, and User Moderation
Amazon IVS Chat is a managed WebSocket chat service with a server-side control API in @aws-sdk/client-ivschat — a separate package from both the standard IVS streaming API and the real-time stages API. MCP server tools wrapping IVS Chat can create and manage chat rooms, issue scoped capability tokens for viewers, inject server-side events into live rooms (polls, moderation notices, reaction counts), disconnect abusive users, and delete individual messages — all without the MCP server holding a WebSocket connection. This guide covers the room lifecycle, the capability token model, the critical difference between SendMessage (client-side, filtered) and SendEvent (server-side, unfiltered), the moderation actions DisconnectUser and DeleteMessage, and the production gotchas that cause token reuse errors and silent message drops.
TL;DR
Use @aws-sdk/client-ivschat for all server-side chat operations. Rooms are persistent resources; tokens are short-lived JWTs scoped to a room. Capability SEND_MESSAGE allows the viewer to send chat messages; DISCONNECT_USER allows them to disconnect other users (moderator token); DELETE_MESSAGE allows message deletion. SendEvent is a server-side operation that bypasses all message filters and content moderation — it delivers an event payload to all connected viewers. SendMessage is a client SDK operation (not a server-side API) — the server does not call it directly. Use DisconnectUser + reason for temporary bans; it disconnects the user's WebSocket and they can rejoin with a new token unless you block re-tokenization in your backend. Message IDs are needed for DeleteMessage — subscribe to room events via EventBridge or store them in your backend at message receipt time.
IVS Chat architecture
IVS Chat is architecturally separate from IVS live streaming and real-time stages. It is a WebSocket-based chat service that clients connect to using the IVS Chat Client Messaging SDK (browser and mobile). The server-side control API — @aws-sdk/client-ivschat — handles room management, token issuance, and moderation actions. The control API never establishes WebSocket connections; it uses standard HTTPS API calls.
The relationship between IVS Chat and other IVS services is loose. A chat room can be paired with any IVS channel or stage by convention (using the same room ARN in your application logic), but there is no binding at the API level — IVS Chat does not know about IVS channels or stages and vice versa. You associate them in your application by passing the chat room ARN to your video player UI alongside the channel playback URL.
IVS Chat rooms persist indefinitely. Each room maintains a message history of configurable size (up to 10,000 messages per room, default 10 messages per room). Connected viewers receive new messages in real time via WebSocket. Viewers who connect after a message is sent can scroll back through the message history up to the room's configured maximum.
SDK installation and client setup
npm install @aws-sdk/client-ivschat
import { IvschatClient } from '@aws-sdk/client-ivschat';
const ivschat = new IvschatClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
IAM permissions: ivschat:CreateRoom, ivschat:GetRoom, ivschat:UpdateRoom, ivschat:DeleteRoom, ivschat:CreateChatToken, ivschat:SendEvent, ivschat:DeleteMessage, ivschat:DisconnectUser, and ivschat:ListRooms. Resource ARN format: arn:aws:ivschat:<region>:<account>:room/<id>.
Room lifecycle
CreateRoomCommand creates a persistent chat room. Configure maximum message rate, maximum message length, and message history size at creation time. These values can be updated later with UpdateRoomCommand — changes take effect immediately for all subsequently sent messages.
import {
IvschatClient,
CreateRoomCommand,
GetRoomCommand,
UpdateRoomCommand,
DeleteRoomCommand,
ListRoomsCommand,
type Room
} from '@aws-sdk/client-ivschat';
const ivschat = new IvschatClient({ region: 'us-east-1' });
async function createChatRoom(params: {
name: string;
maximumMessageRatePerSecond?: number; // 1–10, default 10
maximumMessageLength?: number; // 1–500, default 500
messageReviewHandler?: { uri: string; fallbackResult?: 'ALLOW' | 'DENY' };
tags?: Record<string, string>;
}): Promise<Room> {
const response = await ivschat.send(new CreateRoomCommand({
name: params.name,
maximumMessageRatePerSecond: params.maximumMessageRatePerSecond ?? 10,
maximumMessageLength: params.maximumMessageLength ?? 500,
messageHistoryLimit: 100, // messages stored for scrollback; max 10000
...(params.messageReviewHandler && {
messageReviewHandler: params.messageReviewHandler,
}),
tags: params.tags ?? {},
}));
if (!response.arn) {
throw new Error('CreateRoom returned no ARN');
}
return response as Room;
}
async function listRooms(nameFilter?: string): Promise<Room[]> {
const rooms: Room[] = [];
let nextToken: string | undefined;
do {
const response = await ivschat.send(new ListRoomsCommand({
nextToken,
...(nameFilter && { name: nameFilter }),
}));
rooms.push(...(response.rooms ?? []));
nextToken = response.nextToken;
} while (nextToken);
return rooms;
}
async function updateMessageRate(roomArn: string, ratePerSecond: number): Promise<void> {
await ivschat.send(new UpdateRoomCommand({
identifier: roomArn,
maximumMessageRatePerSecond: ratePerSecond,
}));
}
The messageReviewHandler connects a Lambda function that reviews each user message before delivery. The Lambda receives the message content and attributes, then returns either ALLOW or DENY. The fallbackResult controls behavior if the Lambda errors or times out — use ALLOW to fail open (messages pass through on Lambda failure) or DENY to fail closed. Note that SendEvent (server-side events) bypasses the message review handler entirely; only user-initiated SEND_MESSAGE operations are reviewed.
Message rate limiting (maximumMessageRatePerSecond) is per-connection, not per-room. A user sending messages faster than the limit receives a rate-limit error from the WebSocket and their message is not delivered. The rate limit applies to individual viewer connections — large rooms with thousands of viewers can produce many messages per second in aggregate.
Chat tokens and capability model
Viewers connect to IVS Chat rooms using JWT tokens generated by CreateChatTokenCommand. The token encodes the viewer's identity, capabilities, and expiration. Unlike IVS real-time stage tokens, chat tokens are single-use — each WebSocket connection consumes one token. If a viewer disconnects and reconnects, your server must issue a new token.
import {
IvschatClient,
CreateChatTokenCommand,
type ChatTokenCapability
} from '@aws-sdk/client-ivschat';
const ivschat = new IvschatClient({ region: 'us-east-1' });
type ChatRole = 'viewer' | 'chatter' | 'moderator';
const capabilitiesByRole: Record<ChatRole, ChatTokenCapability[]> = {
viewer: [], // read-only: can receive messages but not send
chatter: ['SEND_MESSAGE'],
moderator: ['SEND_MESSAGE', 'DISCONNECT_USER', 'DELETE_MESSAGE'],
};
async function createChatToken(params: {
roomArn: string;
userId: string;
role: ChatRole;
durationMinutes?: number; // default 60, max 180
attributes?: Record<string, string>;
sessionDurationMinutes?: number; // how long the WebSocket session can last
}): Promise<{ token: string; sessionExpirationTime: Date; tokenExpirationTime: Date }> {
const response = await ivschat.send(new CreateChatTokenCommand({
roomIdentifier: params.roomArn,
userId: params.userId,
capabilities: capabilitiesByRole[params.role],
sessionDurationInMinutes: params.sessionDurationMinutes ?? params.durationMinutes ?? 60,
attributes: params.attributes,
}));
return {
token: response.token!,
sessionExpirationTime: response.sessionExpirationTime!,
tokenExpirationTime: response.tokenExpirationTime!,
};
}
The capability model has three separate capabilities. SEND_MESSAGE allows the viewer to send chat messages via the client SDK. DISCONNECT_USER allows the viewer to initiate a disconnect of another user — this is used for peer moderation features (e.g., trusted moderators who have a special client UI). DELETE_MESSAGE allows the viewer to delete messages from their own client. All three capabilities apply only to actions the viewer takes from their own client SDK; the server-side API can always perform these actions regardless of token capabilities.
Token expiration (tokenExpirationTime) is when the JWT itself expires; the viewer cannot use an expired token to establish a new connection. Session expiration (sessionExpirationTime) is how long an already-established WebSocket connection can last before the server closes it. These are distinct: a viewer might hold an expired token (can't reconnect) but still have an active session (still connected). Set session duration to match your expected stream or event duration — 2–4 hours for live events.
Server-side events vs. client messages
The most important conceptual distinction in IVS Chat: SendEvent and viewer SEND_MESSAGE are fundamentally different operations. SendEvent is a server-side control API call that injects an arbitrary event into the room WebSocket stream — it bypasses the message review handler, all rate limits, and all content moderation. SEND_MESSAGE is what viewers do from the client SDK — it goes through rate limiting and message review. Your MCP server never calls SEND_MESSAGE because it is a client SDK method, not a server API operation.
import {
IvschatClient,
SendEventCommand,
DeleteMessageCommand,
DisconnectUserCommand
} from '@aws-sdk/client-ivschat';
const ivschat = new IvschatClient({ region: 'us-east-1' });
// Server-side event types for a live shopping stream
type StreamEvent =
| { eventName: 'POLL_START'; question: string; options: string[]; durationSeconds: number; pollId: string }
| { eventName: 'POLL_END'; pollId: string; results: Record<string, number> }
| { eventName: 'PRODUCT_SPOTLIGHT'; sku: string; name: string; price: number; url: string; discountPct: number }
| { eventName: 'VIEWER_COUNT'; count: number }
| { eventName: 'MODERATOR_WARNING'; targetUserId: string; reason: string };
async function sendRoomEvent(roomArn: string, event: StreamEvent): Promise<string> {
// Strip eventName from attributes — it's the event name, not an attribute
const { eventName, ...attributes } = event;
// Attributes must be Record<string, string>
const stringAttributes = Object.fromEntries(
Object.entries(attributes).map(([k, v]) => [k, typeof v === 'string' ? v : JSON.stringify(v)])
);
const response = await ivschat.send(new SendEventCommand({
roomIdentifier: roomArn,
eventName, // must be a non-empty string under 100 characters
attributes: stringAttributes,
}));
return response.id ?? '';
}
async function deleteMessage(roomArn: string, messageId: string, reason?: string): Promise<void> {
await ivschat.send(new DeleteMessageCommand({
roomIdentifier: roomArn,
id: messageId,
reason: reason?.substring(0, 256), // reason is optional but helpful for audit logs
}));
}
async function disconnectUser(roomArn: string, userId: string, reason?: string): Promise<void> {
await ivschat.send(new DisconnectUserCommand({
roomIdentifier: roomArn,
userId,
reason: reason?.substring(0, 256),
}));
}
When SendEvent is called, all currently connected viewers receive a WebSocket message with type: "EVENT", the eventName string, and the attributes map. Client SDK event listeners can filter by eventName to dispatch specific UI actions — start a poll timer, show a product card, update the viewer counter. The event is not stored in message history (only SEND_MESSAGE messages appear in history); it is delivered to connected viewers at the moment of the call.
DisconnectUser closes all active WebSocket connections for the specified userId. The user is not permanently banned — they can reconnect if your backend issues them a new token. To implement a durable ban, check a ban list in your token issuance endpoint and refuse to issue tokens for banned users. DisconnectUser provides the immediate enforcement; your backend provides the durable state.
DeleteMessage requires the message ID (id field in the message event). To get message IDs, subscribe to IVS Chat EventBridge events (aws.ivschat source, IVS Chat Message detail-type) or store message IDs in your database as viewers send messages via the client SDK. Without a stored message ID, you cannot delete a specific message after the fact.
Message review handler
The messageReviewHandler is a Lambda function URL (not an API Gateway endpoint — it must be a function URL with InvokeMode: BUFFERED) that IVS Chat calls synchronously for each message before delivery. The Lambda receives a JSON body with the message content, sender attributes, and room ARN, and must respond within 200 ms with an ALLOW or DENY decision.
// Lambda handler for IVS Chat message review
interface MessageReviewRequest {
Content: string;
Attributes: Record<string, string>;
RoomArn: string;
MessageId: string;
UserId: string;
RequestId: string;
}
interface MessageReviewResponse {
ReviewResult: 'ALLOW' | 'DENY';
Content?: string; // optionally replace message content (e.g., to redact PII)
Attributes?: Record<string, string>; // optionally replace attributes
Reason?: string; // shown in IVS console for denied messages
}
export async function handler(event: MessageReviewRequest): Promise<MessageReviewResponse> {
const { Content, UserId, MessageId } = event;
// Basic profanity check (replace with your content moderation service)
const bannedPatterns = [/example-banned-word/i];
for (const pattern of bannedPatterns) {
if (pattern.test(Content)) {
return {
ReviewResult: 'DENY',
Reason: `Message ${MessageId} from ${UserId} matched profanity filter`,
};
}
}
// Check user ban list (from DynamoDB or similar)
// const isBanned = await checkBanList(UserId);
// if (isBanned) return { ReviewResult: 'DENY', Reason: 'User is banned' };
return { ReviewResult: 'ALLOW' };
}
// Lambda function URL config needed in IVS Chat room
const messageReviewHandlerConfig = {
uri: 'https://<function-url-id>.lambda-url.us-east-1.on.aws/',
fallbackResult: 'DENY' as const, // fail closed on Lambda errors
};
The message review Lambda must respond within 200 ms. Lambda cold starts can easily exceed this — ensure the function is warm (use provisioned concurrency or a keep-warm ping) or accept that cold-start messages will be handled by the fallbackResult. Use ALLOW as fallbackResult for a fail-open posture (messages pass through on Lambda error) or DENY for a fail-closed posture. For high-volume chat rooms with strict moderation requirements, fail-closed is safer.
MCP tool handler: chat moderation server
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
IvschatClient,
CreateRoomCommand,
CreateChatTokenCommand,
SendEventCommand,
DeleteMessageCommand,
DisconnectUserCommand,
ListRoomsCommand
} from '@aws-sdk/client-ivschat';
import { z } from 'zod';
const ivschat = new IvschatClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const server = new McpServer({ name: 'ivs-chat', version: '1.0.0' });
server.tool(
'create_chat_room',
'Create an IVS Chat room for a live stream or event',
{
name: z.string().min(1).max(128).describe('Room name'),
maxMessageLength: z.number().int().min(1).max(500).default(500),
messageHistoryLimit: z.number().int().min(1).max(10000).default(100),
},
async ({ name, maxMessageLength, messageHistoryLimit }) => {
const { arn } = await ivschat.send(new CreateRoomCommand({
name,
maximumMessageLength: maxMessageLength,
maximumMessageRatePerSecond: 10,
messageHistoryLimit,
}));
return { content: [{ type: 'text', text: JSON.stringify({ arn, name }, null, 2) }] };
}
);
server.tool(
'create_viewer_token',
'Issue an IVS Chat token for a viewer to join a room',
{
roomArn: z.string().startsWith('arn:aws:ivschat:').describe('IVS Chat room ARN'),
userId: z.string().min(1).max(128).describe('Viewer user ID'),
role: z.enum(['viewer', 'chatter', 'moderator']).default('chatter'),
sessionDurationMinutes: z.number().int().min(1).max(180).default(60),
displayName: z.string().optional(),
},
async ({ roomArn, userId, role, sessionDurationMinutes, displayName }) => {
const capabilities = role === 'moderator'
? ['SEND_MESSAGE' as const, 'DISCONNECT_USER' as const, 'DELETE_MESSAGE' as const]
: role === 'chatter'
? ['SEND_MESSAGE' as const]
: [];
const { token, sessionExpirationTime } = await ivschat.send(new CreateChatTokenCommand({
roomIdentifier: roomArn,
userId,
capabilities,
sessionDurationInMinutes: sessionDurationMinutes,
attributes: displayName ? { displayName } : undefined,
}));
return {
content: [{
type: 'text',
text: JSON.stringify({ token, sessionExpirationTime, capabilities }, null, 2),
}],
};
}
);
server.tool(
'send_room_event',
'Send a server-side event to all connected viewers in an IVS Chat room (bypasses moderation)',
{
roomArn: z.string().startsWith('arn:aws:ivschat:').describe('IVS Chat room ARN'),
eventName: z.string().min(1).max(100).describe('Event type name (e.g., POLL_START, PRODUCT_SPOTLIGHT)'),
attributes: z.record(z.string()).describe('Event data as string key-value pairs'),
},
async ({ roomArn, eventName, attributes }) => {
const { id } = await ivschat.send(new SendEventCommand({
roomIdentifier: roomArn,
eventName,
attributes,
}));
return { content: [{ type: 'text', text: `Event sent (ID: ${id})` }] };
}
);
server.tool(
'delete_chat_message',
'Delete a specific message from an IVS Chat room',
{
roomArn: z.string().startsWith('arn:aws:ivschat:').describe('IVS Chat room ARN'),
messageId: z.string().describe('Message ID (from EventBridge IVS Chat Message event)'),
reason: z.string().max(256).optional(),
},
async ({ roomArn, messageId, reason }) => {
await ivschat.send(new DeleteMessageCommand({
roomIdentifier: roomArn,
id: messageId,
reason,
}));
return { content: [{ type: 'text', text: `Message ${messageId} deleted` }] };
}
);
server.tool(
'disconnect_chat_user',
'Disconnect a user from an IVS Chat room (closes their WebSocket connection)',
{
roomArn: z.string().startsWith('arn:aws:ivschat:').describe('IVS Chat room ARN'),
userId: z.string().describe('User ID to disconnect (they can reconnect with a new token unless blocked)'),
reason: z.string().max(256).optional().describe('Reason code passed to the client SDK disconnect callback'),
},
async ({ roomArn, userId, reason }) => {
await ivschat.send(new DisconnectUserCommand({
roomIdentifier: roomArn,
userId,
reason,
}));
return { content: [{ type: 'text', text: `User ${userId} disconnected from room` }] };
}
);
const transport = new StdioServerTransport();
await server.connect(transport);
EventBridge events for chat
IVS Chat emits EventBridge events for message send, delete, and user connect/disconnect. Subscribe to aws.ivschat source events to build a durable audit log, trigger downstream actions on user connect, or store message IDs for future deletion.
// EventBridge event source: "aws.ivschat"
// Event detail-types:
// "IVS Chat Message" — user sent a message
// "IVS Chat Message Delete" — message was deleted
// "IVS Chat User Disconnect" — user disconnected
interface IvsChatMessageEvent {
'detail-type': 'IVS Chat Message';
source: 'aws.ivschat';
detail: {
messageId: string;
roomArn: string;
userId: string;
content: string;
attributes?: Record<string, string>;
sendTime: string;
requestId: string;
type: 'MESSAGE';
};
}
// EventBridge rule to capture all IVS Chat events
const chatEventRule = {
source: ['aws.ivschat'],
'detail-type': [
'IVS Chat Message',
'IVS Chat Message Delete',
'IVS Chat User Disconnect',
],
};
// Lambda to store message IDs for moderation lookback
async function storeChatMessage(event: IvsChatMessageEvent): Promise<void> {
const { messageId, roomArn, userId, content, sendTime } = event.detail;
// Store in DynamoDB with TTL = sendTime + 24h for 24-hour delete window
// This enables DeleteMessage calls by looking up messageId by content/userId
console.log(`New message: ${messageId} from ${userId} in room ${roomArn}: "${content}"`);
}
Production gotchas
| Gotcha | Symptom | Fix |
|---|---|---|
| Wrong SDK package | IvsClient from client-ivs has no room or token commands |
Import IvschatClient from @aws-sdk/client-ivschat |
| Chat token is single-use | Viewer disconnect + reconnect fails with expired/used token | Issue a new token on every WebSocket connection request; tokens cannot be reused |
| SendEvent bypasses review handler | Server events appear in chat despite room having content moderation | Expected behavior — SendEvent is always unfiltered; validate event data server-side before calling |
| Message review Lambda cold start | First message in room takes 500+ ms; handled by fallbackResult | Use provisioned concurrency or keep-warm ping; use ALLOW fallback for low-moderation rooms |
| No message ID for DeleteMessage | Cannot delete message after the fact — ID not stored anywhere | Subscribe to EventBridge IVS Chat Message events and store messageId in DynamoDB with TTL |
| DisconnectUser doesn't ban permanently | Kicked user rejoins immediately with existing token | DisconnectUser closes WebSocket only; maintain a ban list in your token endpoint to block re-tokenization |
| Message history limit default = 10 | Viewers who join mid-stream see only 10 messages of scrollback | Set messageHistoryLimit to 100–500 at room creation for a usable scrollback buffer |
| Attributes must be string values | SendEvent attributes with non-string values rejected with 400 |
JSON.stringify() nested objects before passing as attribute values |