Blog · Amazon IVS · Live Streaming, WebRTC Stages & Chat for MCP Servers
Amazon IVS for MCP Servers: Three-SDK Architecture, Stream Key Lifecycle, Real-Time Stages, and AI-Driven Chat Moderation
Amazon Interactive Video Service is not one product — it is three separate, loosely coupled services, each with its own SDK package, ARN namespace, IAM permission prefix, and client class. @aws-sdk/client-ivs handles live streaming channels, stream keys, timed metadata injection, and stream health. @aws-sdk/client-ivs-realtime handles WebRTC multi-participant stages with per-token capability scoping. @aws-sdk/client-ivschat handles managed WebSocket chat rooms with server-side event injection and moderation APIs. MCP server developers building AI agents that control live video platforms must understand this three-way split before writing a line of code — importing from the wrong package is the single most common first-hour failure. This guide synthesises the complete IVS control plane across all four sub-topics: live channels, stream keys, and timed metadata; recording to S3 with EventBridge lifecycle events; real-time WebRTC stages and participant management; and chat rooms, server-side events, and user moderation. The synthesis theme: the one-time stream key secret pattern, the dual IAM requirement that causes CREATE_FAILED recording configurations, the participantId-not-userId disconnect gotcha, and the SendEvent-bypasses-moderation invariant that determines how AI agents interact with live audiences.
The three-service architecture: choosing the right SDK before you start
The fundamental decision when building an IVS MCP server is which of the three services you need. Many developers start with @aws-sdk/client-ivs (the original live streaming SDK) and discover mid-implementation that their use case requires real-time stages or chat — both of which are separate packages with separate API surfaces. Making the wrong choice early means refactoring not just imports but ARN patterns, IAM policies, and client initialization throughout the codebase.
| Service | SDK package | Protocol | Primary use case for MCP tools |
|---|---|---|---|
| Live streaming channels | @aws-sdk/client-ivs |
RTMPS ingest → HLS playback | Control and monitor one-broadcaster-to-many-viewers streams: check if live, inject polls, force disconnect, monitor stream health, record to S3 |
| Real-time stages | @aws-sdk/client-ivs-realtime |
WebRTC (sub-300 ms) | Manage multi-participant video rooms: create rooms, generate join tokens with PUBLISH/SUBSCRIBE capabilities, list who is publishing, kick participants for moderation |
| Chat rooms | @aws-sdk/client-ivschat |
WebSocket (IVS Chat Client SDK) | Manage chat alongside a live stream or stage: issue viewer tokens, inject server-side poll/product events, delete messages, disconnect abusive users |
The three services are architecturally independent. A live streaming channel knows nothing about an IVS Chat room you pair with it in your application — the association exists only in your application logic, not in AWS resource relationships. Similarly, an IVS real-time stage and an IVS Chat room are not linked at the API level. You can deploy all three, any two, or just one depending on your platform's needs. For a typical AI-augmented live event platform, an MCP server will use all three: channels for broadcast control, stages for backstage producer rooms, and chat for audience interaction.
IAM policy structure follows the split. Live streaming and stages share the ivs: permission prefix (e.g., ivs:CreateChannel, ivs:CreateStage). Chat uses ivschat: as its prefix. Resource ARNs use different namespaces: arn:aws:ivs:*:*:channel/ for channels, arn:aws:ivs:*:*:stage/ for stages, and arn:aws:ivschat:*:*:room/ for chat rooms. Keeping these distinct in your IAM policies from the start avoids overly broad ivs:* grants that accidentally cross service boundaries.
Live streaming channels: the stream key is a one-time secret
The single most consequential design decision when building an MCP server around IVS live streaming channels is stream key storage. CreateChannelCommand returns both the channel resource and a stream key in one call — and the stream key's secret value is returned only at that moment. No subsequent API call can retrieve the value of an existing stream key. GetStreamKeyCommand returns metadata (ARN, channel ARN, tags, creation time) but never the actual credential string. ListStreamKeysCommand returns the same metadata for all keys on a channel. The secret is permanently inaccessible after the initial creation response.
This means your MCP tool handler has a single opportunity to persist the credential. The correct pattern: immediately after calling CreateChannelCommand or CreateStreamKeyCommand, write the key value to AWS Secrets Manager with a structured JSON payload that includes the channel ARN, key ARN, creation timestamp, and the secret value itself. Any error that occurs between creation and secret storage means the key is permanently lost — the broadcaster cannot ingest, and you must generate a new key (which does not invalidate the old one, so both are now active until you explicitly delete the original).
import {
IvsClient,
CreateChannelCommand,
CreateStreamKeyCommand
} from '@aws-sdk/client-ivs';
import {
SecretsManagerClient,
CreateSecretCommand
} from '@aws-sdk/client-secrets-manager';
const ivs = new IvsClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const secrets = new SecretsManagerClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
async function createChannelWithSecretStorage(name: string) {
const { channel, streamKey } = await ivs.send(new CreateChannelCommand({
name,
type: 'STANDARD',
latencyMode: 'LOW',
}));
if (!channel || !streamKey?.value || !streamKey.arn) {
throw new Error('CreateChannel returned incomplete response');
}
// Store immediately — this is the ONLY time the value is accessible
await secrets.send(new CreateSecretCommand({
Name: `ivs/stream-key/${streamKey.arn.split('/').pop()}`,
SecretString: JSON.stringify({
channelArn: channel.arn,
streamKeyArn: streamKey.arn,
value: streamKey.value,
createdAt: new Date().toISOString(),
}),
}));
return {
channelArn: channel.arn,
ingestEndpoint: channel.ingestEndpoint, // rtmps://<endpoint>:443/app/
playbackUrl: channel.playbackUrl,
streamKeyArn: streamKey.arn,
// Do NOT return streamKey.value in the tool response — it's now in Secrets Manager
};
}
Channel type determines the transcoding ladder. STANDARD (the default) produces multi-rendition HLS with adaptive bitrate. BASIC is passthrough only — no transcoding, no ABR, viewers get exactly what the broadcaster sends at the resolution and bitrate of the ingest stream. ADVANCED_HD and ADVANCED_SD add B-frame encoding for approximately 20–30% compression efficiency gain on high-motion content (e-sports, gaming) at the same visual quality. The tradeoff is slightly higher ingest CPU on the broadcaster's encoder. For MCP servers generating channels programmatically, default to STANDARD and expose type as a Zod enum parameter with a narrow allowed set — do not let agents pick BASIC without understanding its adaptive bitrate limitations.
The other live streaming gotcha that breaks monitoring dashboards: GetStreamCommand throws ChannelNotBroadcasting when no broadcaster is connected. This is a normal channel state, not a service error. Many MCP tool handlers treat all exceptions as errors and return 500 responses to the calling agent. The correct pattern catches this exception by name and returns a typed "channel is idle" response:
async function getStreamStatus(channelArn: string) {
try {
const { stream } = await ivs.send(new GetStreamCommand({ channelArn }));
return {
live: true,
health: stream?.health, // HEALTHY | STARVING | UNKNOWN
viewerCount: stream?.viewerCount,
startTime: stream?.startTime,
streamId: stream?.streamId,
};
} catch (err: unknown) {
if ((err as { name?: string }).name === 'ChannelNotBroadcasting') {
return { live: false }; // normal — not an error
}
throw err;
}
}
PutMetadataCommand injects an arbitrary string payload into the active live stream as a timed metadata event. Players using the Amazon IVS player SDK receive it synchronized to the video timeline. Two constraints matter for MCP tool design: the payload must be under 1 KB serialized, and delivery is best-effort with 2–3 seconds of timing jitter. For polls and product spotlights where the visual must appear at a precise moment in the stream, send the metadata 2–3 seconds before the intended trigger time. For large data payloads (product catalogs, quiz banks), store the data in a CDN-hosted JSON file and send only a reference ID as the metadata payload — the player fetches the full data on receipt. PutMetadata also throws ChannelNotBroadcasting if the channel is idle, so check stream status first in your tool handler before attempting metadata injection.
Recording to S3: the dual IAM requirement that causes CREATE_FAILED
IVS recording to S3 works through a reusable RecordingConfiguration resource that you create once and attach to any number of channels. When a broadcaster starts streaming on an attached channel, IVS automatically begins writing HLS segments, rendition manifests, and optional JPEG thumbnails to your S3 bucket in a structured path pattern.
Recording configurations move through three states: CREATING, ACTIVE, and CREATE_FAILED. Poll GetRecordingConfigurationCommand after creation until the state reaches ACTIVE (typically 10–30 seconds) before attaching to a channel. If the state is CREATE_FAILED, the cause is almost always a permissions problem — specifically, one of two required IAM configurations is missing or incorrect.
The dual IAM requirement is the most common first-time failure when setting up IVS recording:
- IAM service role trust policy: An IAM role with a trust policy allowing
ivs.amazonaws.comto assume it, plus an S3 permissions policy (s3:PutObject,s3:GetObject,s3:ListBucket) on your recording bucket. - S3 bucket policy: An explicit bucket policy allowing the
ivs.amazonaws.comservice principal to write to the bucket, scoped to your account withaws:SourceAccount.
Both are required. Neither alone is sufficient. Developers who configure the IAM role correctly but skip the S3 bucket policy get CREATE_FAILED on the recording configuration with no other error detail. The bucket policy with the aws:SourceAccount condition prevents the IVS service from writing to your bucket on behalf of other AWS accounts — a cross-account confused deputy protection that is both a security requirement and the reason IVS insists on it at configuration time rather than at write time.
// S3 bucket policy — required in ADDITION to the IAM service role
const bucketPolicy = {
Version: '2012-10-17',
Statement: [{
Effect: 'Allow',
Principal: { Service: 'ivs.amazonaws.com' },
Action: ['s3:PutObject', 's3:ListBucket'],
Resource: [
'arn:aws:s3:::your-ivs-recordings-bucket',
'arn:aws:s3:::your-ivs-recordings-bucket/*',
],
Condition: {
StringEquals: { 'aws:SourceAccount': '123456789012' },
},
}],
};
// IAM trust policy on the service role
const trustPolicy = {
Version: '2012-10-17',
Statement: [{
Effect: 'Allow',
Principal: { Service: 'ivs.amazonaws.com' },
Action: 'sts:AssumeRole',
}],
};
An additional KMS complication: if your S3 bucket uses a customer-managed KMS key for server-side encryption, the IVS service role also needs kms:GenerateDataKey and kms:Decrypt in its permissions policy, and the KMS key policy must include a statement allowing ivs.amazonaws.com. Without the KMS grants, the recording configuration transitions to ACTIVE (the IAM validation passes) but the first segment write fails silently — you see no CREATE_FAILED state transition, only an error state in the EventBridge Recording Start Failure event when a broadcaster actually connects.
The S3 output path structure follows a deterministic pattern that your post-processing Lambda or analytics pipeline must understand to locate recordings:
// IVS recording S3 output path:
// <channel-id>/<stream-id>/
// events/
// recording-started.json
// recording-ended.json
// media/
// hls/
// master.m3u8 ← the VOD entry point, available after Recording End event
// high/playlist.m3u8 + *.ts
// medium/playlist.m3u8 + *.ts
// low/playlist.m3u8 + *.ts
// thumbnails/
// latest.jpg (if LATEST storage enabled)
// <timestamp>.jpg (if SEQUENTIAL storage enabled)
// channel-id = last segment of channel ARN
function channelIdFromArn(arn: string): string {
return arn.split('/').pop()!;
}
The critical timing constraint for VOD workflows: the Recording End EventBridge event arrives 20–60 seconds after the broadcaster disconnects. The master.m3u8 file in S3 is not complete — the final HLS segment has not been written — until after this event fires. Any Lambda or post-processing job that generates a presigned VOD URL or triggers transcoding must wait for Recording End. Triggering on the broadcaster disconnect signal (or on GetStream returning ChannelNotBroadcasting) is too early and produces an HLS manifest that players render as a stream cut off mid-broadcast.
Thumbnail configuration is disabled by default. Enable it by setting thumbnailConfiguration.recordingMode to INTERVAL and specifying targetIntervalSeconds. The storage array accepts LATEST (overwrites thumbnails/latest.jpg each interval — useful for live stream gallery previews), SEQUENTIAL (writes thumbnails/<timestamp>.jpg per interval — useful for VOD scrubbing and content moderation review), or both. A 10-hour stream with 30-second thumbnail intervals produces 1,200 objects in the thumbnails/ prefix — factor this into S3 lifecycle policy planning if thumbnails are for temporary use only.
Real-time stages: wrong SDK package, wrong everything
IVS real-time stages are the most commonly misunderstood part of the IVS product family. Developers building a multi-participant video feature start with @aws-sdk/client-ivs (the channel SDK they already know) and find that CreateStageCommand does not exist on the IvsClient class. It never will — stages are a completely separate service with a separate client class (IVSRealTimeClient) from a separate package (@aws-sdk/client-ivs-realtime). This is not an import path typo; it is a fully independent service with different API calls, different ARN prefixes, and different IAM action names.
// WRONG — IvsClient from client-ivs has no stage commands
import { IvsClient } from '@aws-sdk/client-ivs';
// IvsClient.send(new CreateStageCommand(...)) → TypeError: CreateStageCommand undefined
// CORRECT — separate package, separate client
import { IVSRealTimeClient, CreateStageCommand } from '@aws-sdk/client-ivs-realtime';
const ivsRt = new IVSRealTimeClient({ region: 'us-east-1' });
Stages are persistent rooms. Unlike a session that ends when participants leave, a stage resource persists indefinitely until explicitly deleted. For application patterns with recurring rooms (team meeting room, standing game lobby), create once and reuse. For ephemeral rooms (each user session gets a new private room), create at session start and delete at session end — trigger deletion on the IVS Stage Session Ended EventBridge event rather than on participant disconnect, since the session takes a few seconds to close after the last participant leaves.
Participant tokens are the core access control primitive. CreateParticipantTokenCommand generates a short-lived JWT that the client SDK presents when joining the stage. The token encodes the participant's application-layer userId, a set of capabilities, an expiration time (1–20,160 minutes, default 60), and an optional attributes map that is broadcast to all existing participants when this participant joins.
The capability model has two orthogonal permissions: PUBLISH (can send audio and video) and SUBSCRIBE (can receive audio and video from other publishers). Assign both for a standard video call participant, SUBSCRIBE only for a silent observer, and neither for a theoretical "ghost" participant (not useful in practice). The 12-publisher maximum per stage is enforced at WebRTC negotiation time — the 13th participant with PUBLISH capability fails to publish at the SDK level, not at the token-creation level. This means creating a 13th PUBLISH token succeeds without error; the failure manifests only when the participant tries to actually start their media stream. Enforce the 12-publisher limit in your MCP tool handler before issuing PUBLISH tokens:
async function createParticipantTokenSafe(params: {
stageArn: string;
userId: string;
capabilities: ('PUBLISH' | 'SUBSCRIBE')[];
durationMinutes?: number;
attributes?: Record<string, string>;
}) {
// Enforce 12-publisher limit before issuing a PUBLISH token
if (params.capabilities.includes('PUBLISH')) {
const sessionId = await getActiveSessionId(params.stageArn);
if (sessionId) {
const { participants } = await ivsRt.send(new ListParticipantsCommand({
stageArn: params.stageArn,
sessionId,
filterByPublished: true,
}));
if ((participants ?? []).length >= 12) {
throw new Error('Stage has reached the 12-publisher limit');
}
}
}
const { participantToken } = await ivsRt.send(new CreateParticipantTokenCommand({
stageArn: params.stageArn,
userId: params.userId,
capabilities: params.capabilities,
duration: params.durationMinutes ?? 60,
attributes: params.attributes ?? {},
}));
return participantToken;
}
The participantId versus userId distinction is the most common source of ResourceNotFoundException when calling DisconnectParticipantCommand. The userId is the application-layer identifier you encoded in the token with CreateParticipantTokenCommand. The participantId is an IVS-generated UUID assigned when the participant joins a session — it is different from userId, and it changes on every reconnect. DisconnectParticipantCommand requires the IVS-assigned participantId, not the application userId. Always fetch the current participantId from ListParticipantsCommand immediately before calling DisconnectParticipant rather than caching it, since it changes on reconnect.
Listing participants also requires knowing the current session ID. ListParticipantsCommand takes a sessionId parameter — it cannot list participants across all sessions of a stage. Use ListStageSessionsCommand first to find the active session (the one with no endTime), then use that session's ID for ListParticipants. If no session is active, return an empty participants list rather than throwing an error:
async function getActiveSessionId(stageArn: string): Promise<string | null> {
const { stageSessions } = await ivsRt.send(
new ListStageSessionsCommand({ stageArn })
);
if (!stageSessions?.length) return null;
const latest = stageSessions[0]; // sessions ordered newest first
return latest.endTime ? null : (latest.sessionId ?? null);
}
Token expiration requires client-side handling. The IVS Web Broadcast SDK fires a token-expiring warning callback at 30 seconds before expiry. Your client must use this callback to request a new token from your server and pass it to the SDK for a seamless refresh — if the token expires without a refresh, the participant silently loses the ability to send and receive media without disconnecting. For MCP server design, this means your create_participant_token tool should accept a durationMinutes parameter that your application sets based on the expected session length plus a generous buffer.
IVS Chat: SendEvent bypasses everything the reviewer was built to stop
IVS Chat is architecturally decoupled from both live streaming channels and real-time stages. It is a managed WebSocket chat service with a server-side control API in @aws-sdk/client-ivschat — a third separate package. The IvschatClient class (note: lowercase c in chat within Ivschat) handles room management, token issuance, and all moderation actions. The control API uses standard HTTPS calls; it never establishes WebSocket connections itself.
The critical conceptual distinction in IVS Chat that determines how MCP server tools should be structured: SendEvent and SEND_MESSAGE are fundamentally different operations. SendEvent is a server-side control API call (SendEventCommand in the @aws-sdk/client-ivschat package) that injects an arbitrary event payload into the room WebSocket stream. It bypasses the message review handler, all rate limits, all content moderation, and all capability checks. SEND_MESSAGE is a client SDK method that viewers call from the browser — your MCP server never calls it and cannot call it, because it is part of the client-side WebSocket library, not a server API operation. Many developers search for a SendMessageCommand in the server SDK and cannot find it; this is intentional.
// SendEvent — server-side, bypasses review handler
// Use for: polls, product spotlights, moderation notices, viewer counts
// MCP server DOES call this directly
await ivschat.send(new SendEventCommand({
roomIdentifier: roomArn,
eventName: 'POLL_START', // non-empty string, max 100 chars
attributes: { // must be Record<string, string> — not nested objects
question: 'Which feature should we build next?',
options: JSON.stringify(['Dashboard improvements', 'Mobile app', 'API access']),
durationSeconds: '30',
pollId: 'poll-2026-11-19-001',
},
}));
// SEND_MESSAGE — client-side WebSocket SDK
// MCP server CANNOT call this — it does not exist in @aws-sdk/client-ivschat
// Viewers call it from their browser via the IVS Chat Client Messaging SDK
The practical consequence for AI-driven live event moderation: an MCP tool that injects polls, product spotlight overlays, or quiz reveal events uses SendEvent and always succeeds regardless of whether the room has a message review handler configured. This is correct and expected behavior — server-side control events are trusted first-party injections, not user-generated content requiring moderation. Validate the event data server-side in your MCP tool handler before calling SendEvent; that validation is your only safeguard since the room's review handler will not see these events.
Chat tokens are single-use JWTs. Unlike IVS real-time stage participant tokens (which can be used to reconnect), each IVS Chat token creates exactly one WebSocket connection. When a viewer disconnects — network blip, browser tab closed, mobile background — they cannot reconnect with the same token. Your server must issue a new token on every connection request. This design is intentional: it means every connection carries fresh capability grants and attributes, which simplifies server-side state management. Build your token endpoint to issue tokens unconditionally on each request rather than trying to detect and reuse live tokens.
async function issueChatToken(params: {
roomArn: string;
userId: string;
role: 'viewer' | 'chatter' | 'moderator';
displayName?: string;
sessionDurationMinutes?: number;
}) {
const capabilitiesByRole = {
viewer: [] as const,
chatter: ['SEND_MESSAGE'] as const,
moderator: ['SEND_MESSAGE', 'DISCONNECT_USER', 'DELETE_MESSAGE'] as const,
};
const { token, sessionExpirationTime } = await ivschat.send(
new CreateChatTokenCommand({
roomIdentifier: params.roomArn,
userId: params.userId,
capabilities: capabilitiesByRole[params.role],
sessionDurationInMinutes: params.sessionDurationMinutes ?? 60,
attributes: params.displayName ? { displayName: params.displayName } : undefined,
})
);
return { token, sessionExpirationTime };
// token is single-use — issue a new one on every reconnect
}
The capability model has three separate grants: SEND_MESSAGE allows the viewer to send chat messages, DISCONNECT_USER allows peer-moderation (trusted moderators can disconnect other users from their client), and DELETE_MESSAGE allows message deletion from the client. These capabilities apply to actions the viewer takes from their own client SDK — the server-side API can always perform these actions regardless of token capabilities.
Message deletion from the server side requires a stored message ID. DeleteMessageCommand takes the message ID (id field) which is only available in the IVS Chat Message EventBridge event, not in any server API response. To build a "delete last message from user X" MCP tool, you must maintain a message ID store — a DynamoDB table with a TTL equal to your desired deletion window (24 hours is typical), populated by a Lambda subscribed to aws.ivschat EventBridge events. Without this store, you cannot delete a specific message after the fact.
User disconnection is not durable banning. DisconnectUserCommand closes all active WebSocket connections for the specified userId — it disconnects them immediately from every room session they are connected to. But the user can immediately 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 is the enforcement action; your backend ban list is the state. Without the backend state, a human moderator disconnecting a user achieves nothing — the user is back in chat in under a second.
Cross-cutting concern: EventBridge as the IVS event bus
All three IVS services emit EventBridge events that form the backbone of any reactive IVS-backed platform. Understanding which events each service emits, and what data they carry, is essential for building reliable MCP server workflows.
| Service | EventBridge source | Key events | MCP server use case |
|---|---|---|---|
| Live streaming | aws.ivs |
IVS Stream State Change (LIVE/OFFLINE), IVS Stream Health Change (STARVING) |
Trigger AI content moderation on stream start; alert on STARVING health |
| Recording | aws.ivs |
IVS Recording State Change (Recording Start, Recording End, Recording Start/End Failure) |
Trigger VOD post-processing Lambda on Recording End; alert on Recording Start Failure |
| Real-time stages | aws.ivs |
IVS Stage Session Started, IVS Stage Session Ended, IVS Participant Joined, IVS Participant Left |
Auto-delete ephemeral stages on Session Ended; track participant join/leave for analytics |
| Chat | aws.ivschat |
IVS Chat Message (with messageId), IVS Chat Message Delete, IVS Chat User Disconnect |
Store messageId in DynamoDB for deletion lookback; feed message stream to AI content moderation |
The recording timing constraint bears repeating: the IVS Recording State Change event with recording_status: "Recording End" arrives 20–60 seconds after the broadcaster disconnects. The recording_sessions array in the event detail contains one S3 key prefix per session when the stream had reconnects within the recordingReconnectWindowSeconds window — iterate all prefixes in your post-processing handler, not just the first one, or you will miss the continuation segments from reconnect scenarios.
For MCP servers that need VOD playback URLs immediately after a recording ends, the correct pipeline is: subscribe to the Recording End EventBridge event → trigger a Lambda that generates a presigned URL for <channel-id>/<stream-id>/media/hls/master.m3u8 → store the URL in a database keyed by stream ID → expose a get_vod_url MCP tool that queries the database. Do not attempt to generate the presigned URL synchronously in a GetStream call or broadcast-end webhook — the HLS manifest is not complete until after the EventBridge event fires.
Full MCP server: live streaming control plane with recording and health monitoring
The following MCP server wraps the core live streaming control plane (@aws-sdk/client-ivs) with five tools: create a channel (with immediate stream key Secrets Manager storage), get stream status (with ChannelNotBroadcasting as a non-error), send timed metadata, stop a stream, and list all degraded streams across the account. This pattern is the foundation for an AI agent that monitors and controls a fleet of live streaming channels.
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
IvsClient,
CreateChannelCommand,
GetStreamCommand,
PutMetadataCommand,
StopStreamCommand,
ListStreamsCommand,
CreateStreamKeyCommand
} from '@aws-sdk/client-ivs';
import { SecretsManagerClient, CreateSecretCommand } from '@aws-sdk/client-secrets-manager';
import { z } from 'zod';
const ivs = new IvsClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const secrets = new SecretsManagerClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const server = new McpServer({ name: 'ivs-control-plane', version: '1.0.0' });
server.tool(
'create_ivs_channel',
'Create an IVS live streaming channel; stream key is stored to Secrets Manager automatically',
{
name: z.string().min(1).max(128),
type: z.enum(['STANDARD', 'ADVANCED_HD', 'ADVANCED_SD', 'BASIC']).default('STANDARD'),
recordingConfigurationArn: z.string().optional(),
},
async ({ name, type, recordingConfigurationArn }) => {
const { channel, streamKey } = await ivs.send(new CreateChannelCommand({
name, type, latencyMode: 'LOW',
...(recordingConfigurationArn && { recordingConfigurationArn }),
}));
if (!channel || !streamKey?.value) throw new Error('Incomplete CreateChannel response');
const secretName = `ivs/stream-key/${streamKey.arn?.split('/').pop()}`;
await secrets.send(new CreateSecretCommand({
Name: secretName,
SecretString: JSON.stringify({
channelArn: channel.arn,
streamKeyArn: streamKey.arn,
value: streamKey.value,
createdAt: new Date().toISOString(),
}),
}));
return {
content: [{
type: 'text',
text: JSON.stringify({
channelArn: channel.arn,
ingestEndpoint: `rtmps://${channel.ingestEndpoint}:443/app/`,
playbackUrl: channel.playbackUrl,
streamKeyArn: streamKey.arn,
streamKeySecret: secretName, // retrieve from Secrets Manager to get the actual value
}, null, 2),
}],
};
}
);
server.tool(
'get_stream_status',
'Get the live status of an IVS channel — not live is a valid non-error state',
{ channelArn: z.string().startsWith('arn:aws:ivs:') },
async ({ channelArn }) => {
try {
const { stream } = await ivs.send(new GetStreamCommand({ channelArn }));
return {
content: [{
type: 'text',
text: JSON.stringify({
live: true,
health: stream?.health,
viewerCount: stream?.viewerCount,
startTime: stream?.startTime,
streamId: stream?.streamId,
}, null, 2),
}],
};
} catch (err: unknown) {
if ((err as { name?: string }).name === 'ChannelNotBroadcasting') {
return { content: [{ type: 'text', text: JSON.stringify({ live: false }) }] };
}
throw err;
}
}
);
server.tool(
'send_stream_metadata',
'Inject a timed metadata payload into a live IVS stream (polls, product spotlights, quiz reveals)',
{
channelArn: z.string().startsWith('arn:aws:ivs:'),
payload: z.record(z.unknown()).describe('JSON object to deliver (must serialize to under 1 KB)'),
},
async ({ channelArn, payload }) => {
const serialized = JSON.stringify(payload);
const bytes = Buffer.byteLength(serialized, 'utf8');
if (bytes > 1024) {
return { content: [{ type: 'text', text: `Error: ${bytes} bytes exceeds 1024-byte limit` }], isError: true };
}
try {
await ivs.send(new PutMetadataCommand({ channelArn, metadata: serialized }));
return { content: [{ type: 'text', text: `Metadata injected (${bytes} bytes, delivery jitter 2–3 s)` }] };
} catch (err: unknown) {
if ((err as { name?: string }).name === 'ChannelNotBroadcasting') {
return { content: [{ type: 'text', text: 'Error: channel is not currently live' }], isError: true };
}
throw err;
}
}
);
server.tool(
'stop_live_stream',
'Force-disconnect the broadcaster from an active IVS stream',
{ channelArn: z.string().startsWith('arn:aws:ivs:') },
async ({ channelArn }) => {
await ivs.send(new StopStreamCommand({ channelArn }));
return { content: [{ type: 'text', text: 'Stream stopped — broadcaster has been disconnected' }] };
}
);
server.tool(
'list_degraded_streams',
'List all IVS channels currently in STARVING health state (low ingest bitrate)',
{},
async () => {
const streams = [];
let nextToken: string | undefined;
do {
const response = await ivs.send(new ListStreamsCommand({
nextToken,
filterBy: { health: 'STARVING' },
}));
streams.push(...(response.streams ?? []));
nextToken = response.nextToken;
} while (nextToken);
return { content: [{ type: 'text', text: JSON.stringify(streams, null, 2) }] };
}
);
const transport = new StdioServerTransport();
await server.connect(transport);
Full MCP server: chat moderation with server-side event injection
The following MCP server wraps the IVS Chat control API with the five most useful AI-driven moderation and audience engagement tools: issue chat tokens by role, send a server-side event (poll, product, announcement), delete a message by ID, disconnect an abusive user, and retrieve the current room configuration.
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
IvschatClient,
CreateChatTokenCommand,
SendEventCommand,
DeleteMessageCommand,
DisconnectUserCommand,
GetRoomCommand
} 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-moderator', version: '1.0.0' });
server.tool(
'issue_viewer_token',
'Issue a single-use IVS Chat token for a viewer to connect to a room',
{
roomArn: z.string().startsWith('arn:aws:ivschat:'),
userId: z.string().min(1).max(128),
role: z.enum(['viewer', 'chatter', 'moderator']).default('chatter'),
displayName: z.string().max(128).optional(),
sessionDurationMinutes: z.number().int().min(1).max(180).default(60),
},
async ({ roomArn, userId, role, displayName, sessionDurationMinutes }) => {
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, // single-use JWT — pass to client SDK
sessionExpirationTime,
capabilities,
warning: 'token is single-use — issue a new one on reconnect',
}, null, 2),
}],
};
}
);
server.tool(
'broadcast_room_event',
'Send a server-side event to all viewers in an IVS Chat room (bypasses moderation — validate data before calling)',
{
roomArn: z.string().startsWith('arn:aws:ivschat:'),
eventName: z.string().min(1).max(100),
attributes: z.record(z.string()).describe('String key-value pairs; JSON.stringify nested objects first'),
},
async ({ roomArn, eventName, attributes }) => {
const { id } = await ivschat.send(new SendEventCommand({
roomIdentifier: roomArn,
eventName,
attributes,
}));
return { content: [{ type: 'text', text: `Event broadcast (ID: ${id}); not stored in room history` }] };
}
);
server.tool(
'delete_chat_message',
'Delete a specific message from an IVS Chat room by message ID',
{
roomArn: z.string().startsWith('arn:aws:ivschat:'),
messageId: z.string().describe('Message ID from EventBridge IVS Chat Message event or DynamoDB store'),
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 WebSocket; user can rejoin unless backend blocks re-tokenization)',
{
roomArn: z.string().startsWith('arn:aws:ivschat:'),
userId: z.string().describe('User ID (not token or session ID)'),
reason: z.string().max(256).optional(),
},
async ({ roomArn, userId, reason }) => {
await ivschat.send(new DisconnectUserCommand({
roomIdentifier: roomArn,
userId,
reason,
}));
return {
content: [{
type: 'text',
text: `User ${userId} disconnected. For durable ban: also block re-tokenization in your token endpoint.`,
}],
};
}
);
const transport = new StdioServerTransport();
await server.connect(transport);
Production gotchas across all three IVS services
| Gotcha | Service | Symptom | Fix |
|---|---|---|---|
| Wrong SDK package for stages | Stages | CreateStageCommand undefined when imported from client-ivs |
Install and import from @aws-sdk/client-ivs-realtime; use IVSRealTimeClient |
| Wrong SDK package for chat | Chat | CreateRoomCommand undefined; searching for SendMessageCommand in server SDK fails |
Install @aws-sdk/client-ivschat; use IvschatClient; server never calls SEND_MESSAGE |
| Stream key value not stored after creation | Channels | GetStreamKey returns metadata but no secret; broadcaster cannot ingest |
Store streamKey.value to Secrets Manager immediately after CreateChannel or CreateStreamKey |
ChannelNotBroadcasting treated as error |
Channels | Tool crashes when polling an idle channel; monitoring dashboard shows error storms | Catch by name; return { live: false } — it is a normal, expected channel state |
| Missing S3 bucket policy on recording config | Recording | CREATE_FAILED on RecordingConfiguration despite correctly configured IAM role |
Add explicit bucket policy allowing ivs.amazonaws.com service principal to s3:PutObject |
Reading VOD URL before Recording End event |
Recording | HLS manifest appears truncated; VOD players show stream cut off mid-broadcast | Trigger VOD URL generation on EventBridge Recording End event (20–60 s after disconnect) |
Using userId in DisconnectParticipant |
Stages | ResourceNotFoundException — IVS requires participantId, not application userId |
Call ListParticipants first to get current participantId; it changes on every reconnect |
Stale session ID in ListParticipants |
Stages | ResourceNotFoundException when session has ended |
Call ListStageSessionsCommand first; filter to session with !endTime; return empty list if none active |
| Chat token reuse after disconnect | Chat | Viewer disconnect + reconnect fails with expired/consumed token | Chat tokens are single-use — issue a new token on every WebSocket connection request |
No message ID for DeleteMessage |
Chat | Cannot delete specific message — ID is not returned by any server-side list API | Store messageId in DynamoDB with TTL via EventBridge IVS Chat Message Lambda handler |
DisconnectUser does not permanently ban |
Chat | Kicked user rejoins immediately with a new token | Maintain a ban list in your token endpoint; refuse CreateChatToken calls for banned userIds |
| Max 12 publishers per stage not enforced at token creation | Stages | 13th publisher token creates successfully; participant fails at WebRTC negotiation | Check ListParticipants filterByPublished=true count before issuing PUBLISH tokens; reject if ≥ 12 |
| PutMetadata payload over 1 KB | Channels | 400 Bad Request from API; tool returns error mid-stream | Serialize and measure bytes before sending; use CDN references for large payloads |
| SendEvent attributes not all strings | Chat | 400 error from SendEventCommand with nested object in attributes map |
JSON.stringify() nested objects before passing as attribute values |
Related pages in this series
- Amazon IVS for MCP servers — live channels, stream keys, and timed metadata
- IVS recording to S3 — RecordingConfiguration lifecycle, thumbnails, and EventBridge events
- IVS real-time stages — WebRTC stages, participant tokens, and session management
- IVS Chat — chat rooms, server-side events, and user moderation