Guide · Amazon IVS · Real-Time Stages, WebRTC & Participant Management
Amazon IVS Real-Time Stages for MCP Servers — WebRTC Stages, Participant Tokens, and Session Management
Amazon IVS real-time stages are WebRTC-based multi-participant video rooms distinct from IVS's standard live streaming channels — they use a separate SDK package (@aws-sdk/client-ivs-realtime), different ARN prefixes, and a different participant join flow. An MCP server wrapping the IVS real-time API can create stages on demand, generate scoped participant tokens with PUBLISH or SUBSCRIBE capabilities, list currently connected participants, and forcibly disconnect specific participants for moderation. This guide covers the stage and token lifecycle, the capability model, participant attribute passing, the ListParticipants and GetParticipant pattern for session introspection, and the production gotchas that cause token expiry and participant list drift.
TL;DR
Use @aws-sdk/client-ivs-realtime (not @aws-sdk/client-ivs) for real-time stages. A stage is a persistent room resource with its own ARN; participant tokens are short-lived JWTs generated server-side by CreateParticipantTokenCommand. Token capabilities: PUBLISH allows the participant to send audio/video, SUBSCRIBE allows receiving — assign both for a standard video call participant, SUBSCRIBE only for a silent observer. Tokens expire (default 60 minutes, max 20160 minutes). Use ListParticipantsCommand with filterByPublished to find who is currently sending video. DisconnectParticipantCommand immediately kicks a participant — they must re-request a token to rejoin. Stages and sessions are distinct: a stage can persist indefinitely while session resources are created each time participants connect.
Stages vs. standard IVS channels
IVS real-time stages and standard IVS live streaming channels address fundamentally different use cases. Standard channels support one broadcaster sending to many viewers at low latency (sub-five-second) via HLS. Real-time stages support multiple participants sending audio and video to each other at ultra-low latency (under 300 ms round-trip) via WebRTC. The distinction determines which SDK package, which ARN namespace, and which IAM permission prefix you use.
| Dimension | Standard Channel | Real-Time Stage |
|---|---|---|
| Protocol | RTMPS ingest → HLS playback | WebRTC (browser or mobile SDK) |
| Latency | 2–5 seconds | <300 ms |
| Max senders | 1 broadcaster | 12 publishers per stage |
| Max viewers | Unlimited (CDN) | 10,000 subscribers per stage |
| SDK package | @aws-sdk/client-ivs | @aws-sdk/client-ivs-realtime |
| ARN prefix | arn:aws:ivs:*:*:channel/ | arn:aws:ivs:*:*:stage/ |
| IAM prefix | ivs: | ivs: (same prefix, different actions) |
| Encoder | OBS, FFmpeg, hardware encoders | IVS Web Broadcast SDK, iOS/Android SDK |
For MCP server use cases: use a standard channel when an AI agent needs to control or monitor a one-to-many broadcast (live event, educational stream, e-commerce show). Use a real-time stage when an AI agent needs to manage a multi-participant room (video consultation, interview, collaborative session, online game lobby).
SDK installation and client setup
npm install @aws-sdk/client-ivs-realtime
import { IVSRealTimeClient } from '@aws-sdk/client-ivs-realtime';
const ivsRt = new IVSRealTimeClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
IAM permissions needed: ivs:CreateStage, ivs:GetStage, ivs:UpdateStage, ivs:DeleteStage, ivs:CreateParticipantToken, ivs:ListStageSessions, ivs:GetStageSession, ivs:ListParticipants, ivs:GetParticipant, and ivs:DisconnectParticipant. These actions use the resource ARN arn:aws:ivs:<region>:<account>:stage/<id>.
IVS real-time is available in the same regions as standard IVS: us-east-1, us-west-2, eu-west-1, and ap-northeast-1. The WebRTC media plane uses regional edge infrastructure; participant tokens are region-scoped and cannot be reused across regions.
Creating a stage
CreateStageCommand creates a persistent stage resource. Stages are not destroyed when all participants leave — they persist until explicitly deleted. Create one stage per logical "room" in your application. For ephemeral rooms (each user session gets a new room), create the stage at room creation time and delete it when the session ends. For persistent rooms (recurring team meeting room, standing game lobby), create once and reuse indefinitely.
import {
IVSRealTimeClient,
CreateStageCommand,
GetStageCommand,
DeleteStageCommand,
type Stage
} from '@aws-sdk/client-ivs-realtime';
const ivsRt = new IVSRealTimeClient({ region: 'us-east-1' });
async function createStage(params: {
name: string;
tags?: Record<string, string>;
autoParticipantRecordingConfiguration?: {
storageConfigurationArn: string;
mediaTypes?: ('AUDIO_VIDEO' | 'AUDIO_ONLY')[];
};
}): Promise<Stage> {
const response = await ivsRt.send(new CreateStageCommand({
name: params.name,
tags: params.tags ?? {},
...(params.autoParticipantRecordingConfiguration && {
autoParticipantRecordingConfiguration: params.autoParticipantRecordingConfiguration,
}),
}));
if (!response.stage) {
throw new Error('CreateStage returned no stage object');
}
return response.stage;
}
async function getStage(stageArn: string): Promise<Stage | undefined> {
const { stage } = await ivsRt.send(new GetStageCommand({ arn: stageArn }));
return stage;
}
async function deleteStage(stageArn: string): Promise<void> {
await ivsRt.send(new DeleteStageCommand({ arn: stageArn }));
}
CreateStageCommand returns the stage and optionally a list of participant tokens if you pass participantTokenConfigurations in the same call. This combined create-and-tokenize pattern is useful for single-host stages where the creator immediately needs a token. For multi-participant flows, create the stage first and generate tokens on demand as participants request to join.
Participant token lifecycle and capabilities
Participant tokens are short-lived JWTs generated by the server and passed to the client SDK. The client presents the token when joining the stage via the IVS Web Broadcast SDK or mobile SDK. The token encodes the participant's identity, capabilities, and expiration time — the client SDK validates it locally without a network round-trip. Tokens cannot be revoked after issuance; to remove a participant before their token expires, use DisconnectParticipantCommand.
import {
IVSRealTimeClient,
CreateParticipantTokenCommand,
type ParticipantToken
} from '@aws-sdk/client-ivs-realtime';
const ivsRt = new IVSRealTimeClient({ region: 'us-east-1' });
async function createParticipantToken(params: {
stageArn: string;
userId: string;
capabilities: ('PUBLISH' | 'SUBSCRIBE')[];
durationMinutes?: number; // 1–20160, default 60
attributes?: Record<string, string>; // visible to other participants
}): Promise<ParticipantToken> {
const response = await ivsRt.send(new CreateParticipantTokenCommand({
stageArn: params.stageArn,
userId: params.userId,
capabilities: params.capabilities,
duration: params.durationMinutes ?? 60,
attributes: params.attributes ?? {},
}));
if (!response.participantToken) {
throw new Error('CreateParticipantToken returned no token');
}
return response.participantToken;
}
// Role-based token factories
async function createHostToken(stageArn: string, userId: string) {
return createParticipantToken({
stageArn,
userId,
capabilities: ['PUBLISH', 'SUBSCRIBE'],
durationMinutes: 120,
attributes: { role: 'host', displayName: userId },
});
}
async function createGuestToken(stageArn: string, userId: string) {
return createParticipantToken({
stageArn,
userId,
capabilities: ['PUBLISH', 'SUBSCRIBE'],
durationMinutes: 60,
attributes: { role: 'guest', displayName: userId },
});
}
async function createObserverToken(stageArn: string, userId: string) {
return createParticipantToken({
stageArn,
userId,
capabilities: ['SUBSCRIBE'], // subscribe only — cannot publish audio/video
durationMinutes: 480,
attributes: { role: 'observer' },
});
}
Capabilities determine what the participant can do on the WebRTC media plane. PUBLISH allows sending audio and video tracks. SUBSCRIBE allows receiving audio and video from other publishers. A participant with only SUBSCRIBE can observe the stage but their camera and microphone are never shared. A participant with neither capability (empty array) can join the stage but neither send nor receive media — this is not useful in practice.
The attributes object is an arbitrary string-to-string map encoded in the token and broadcast to all participants when this participant joins. Other participants' SDKs receive it in the participantJoined event. Use it for display names, roles, seat assignments, and application-specific metadata. Keys and values are both limited to 128 characters each; the total attributes object cannot exceed 1 KB serialized.
Token duration defaults to 60 minutes. For scheduled events with known end times, set duration to the event duration plus a buffer. For open-ended rooms, use a moderate duration (2–4 hours) and issue a new token before expiry — the IVS Web Broadcast SDK fires a token-expiring warning callback at 30 seconds before expiry, giving your client time to fetch a renewal token. Generating the renewal token requires a server call to CreateParticipantToken; the token cannot be refreshed client-side.
Listing and monitoring stage participants
ListParticipantsCommand returns the participants in a specific stage session (not across all sessions). A stage session is the period of continuous activity from the first participant joining to some time after the last participant leaves. Each session has its own session ID. Use ListStageSessionsCommand first to get the active session, then pass the session ID to ListParticipants.
import {
IVSRealTimeClient,
ListStageSessionsCommand,
ListParticipantsCommand,
GetParticipantCommand,
DisconnectParticipantCommand,
type Participant
} from '@aws-sdk/client-ivs-realtime';
const ivsRt = new IVSRealTimeClient({ region: 'us-east-1' });
async function getActiveSessionId(stageArn: string): Promise<string | null> {
const { stageSessions } = await ivsRt.send(new ListStageSessionsCommand({
stageArn,
// paginate if needed — sessions are ordered newest first
}));
if (!stageSessions?.length) return null;
// First session in the list is the most recent
const latest = stageSessions[0];
// A session with no endTime is still active
if (!latest.endTime) return latest.sessionId ?? null;
return null; // most recent session has ended — no active session
}
async function listActiveParticipants(
stageArn: string,
options?: {
filterByPublished?: boolean; // only participants currently sending video
filterByUserId?: string;
filterByRecordingState?: 'STARTING' | 'ACTIVE' | 'STOPPING' | 'STOPPED' | 'FAILED';
}
): Promise<Participant[]> {
const sessionId = await getActiveSessionId(stageArn);
if (!sessionId) return [];
const participants: Participant[] = [];
let nextToken: string | undefined;
do {
const response = await ivsRt.send(new ListParticipantsCommand({
stageArn,
sessionId,
nextToken,
filterByPublished: options?.filterByPublished,
filterByUserId: options?.filterByUserId,
filterByRecordingState: options?.filterByRecordingState,
}));
participants.push(...(response.participants ?? []));
nextToken = response.nextToken;
} while (nextToken);
return participants;
}
async function getParticipant(
stageArn: string,
sessionId: string,
participantId: string
): Promise<Participant | undefined> {
const { participant } = await ivsRt.send(new GetParticipantCommand({
stageArn,
sessionId,
participantId,
}));
return participant;
}
async function disconnectParticipant(
stageArn: string,
participantId: string,
reason?: string
): Promise<void> {
await ivsRt.send(new DisconnectParticipantCommand({
stageArn,
participantId,
reason: reason?.substring(0, 128), // reason is limited to 128 characters
}));
}
The Participant object returned by ListParticipants and GetParticipant includes participantId (the IVS-assigned ID, not the userId from the token), userId, state (CONNECTED or DISCONNECTED), published (boolean — currently sending media), firstJoinTime, and the attributes map from their token.
Important: participantId and userId are different. The userId is the application-layer identifier you encoded in the token with CreateParticipantToken. The participantId is an IVS-generated UUID assigned when the participant joins a session. The same user can have multiple participant records in a session if they disconnect and reconnect (each reconnect gets a new participantId but keeps the same userId). When disconnecting a participant, use participantId from ListParticipants, not the userId.
MCP tool handler: stage management server
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
IVSRealTimeClient,
CreateStageCommand,
CreateParticipantTokenCommand,
ListStageSessionsCommand,
ListParticipantsCommand,
DisconnectParticipantCommand,
DeleteStageCommand
} from '@aws-sdk/client-ivs-realtime';
import { z } from 'zod';
const ivsRt = new IVSRealTimeClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const server = new McpServer({ name: 'ivs-stages', version: '1.0.0' });
server.tool(
'create_stage',
'Create an IVS real-time stage (WebRTC video room)',
{
name: z.string().min(1).max(128).describe('Stage name'),
tags: z.record(z.string()).optional(),
},
async ({ name, tags }) => {
const { stage } = await ivsRt.send(new CreateStageCommand({ name, tags }));
return { content: [{ type: 'text', text: JSON.stringify({ arn: stage?.arn, name: stage?.name }, null, 2) }] };
}
);
server.tool(
'create_participant_token',
'Generate a participant token for a user to join an IVS real-time stage',
{
stageArn: z.string().startsWith('arn:aws:ivs:').describe('IVS stage ARN'),
userId: z.string().min(1).max(128).describe('Application user ID to encode in the token'),
role: z.enum(['host', 'guest', 'observer']).default('guest')
.describe('host/guest = PUBLISH+SUBSCRIBE; observer = SUBSCRIBE only'),
durationMinutes: z.number().int().min(1).max(20160).default(60),
attributes: z.record(z.string()).optional().describe('Metadata broadcast to other participants on join'),
},
async ({ stageArn, userId, role, durationMinutes, attributes }) => {
const capabilities = role === 'observer'
? ['SUBSCRIBE' as const]
: ['PUBLISH' as const, 'SUBSCRIBE' as const];
const { participantToken } = await ivsRt.send(new CreateParticipantTokenCommand({
stageArn,
userId,
capabilities,
duration: durationMinutes,
attributes: { role, ...attributes },
}));
return {
content: [{
type: 'text',
text: JSON.stringify({
token: participantToken?.token, // JWT — pass to client SDK
participantId: participantToken?.participantId,
expirationTime: participantToken?.expirationTime,
capabilities,
}, null, 2),
}],
};
}
);
server.tool(
'list_stage_participants',
'List participants currently in an active IVS stage session',
{
stageArn: z.string().startsWith('arn:aws:ivs:').describe('IVS stage ARN'),
publishingOnly: z.boolean().default(false).describe('Filter to only participants sending video'),
},
async ({ stageArn, publishingOnly }) => {
// Get active session
const { stageSessions } = await ivsRt.send(new ListStageSessionsCommand({ stageArn }));
const activeSession = stageSessions?.find(s => !s.endTime);
if (!activeSession?.sessionId) {
return { content: [{ type: 'text', text: JSON.stringify({ participants: [], sessionActive: false }) }] };
}
const { participants } = await ivsRt.send(new ListParticipantsCommand({
stageArn,
sessionId: activeSession.sessionId,
filterByPublished: publishingOnly || undefined,
}));
return {
content: [{
type: 'text',
text: JSON.stringify({
sessionId: activeSession.sessionId,
participants: (participants ?? []).map(p => ({
participantId: p.participantId,
userId: p.userId,
state: p.state,
published: p.published,
attributes: p.attributes,
firstJoinTime: p.firstJoinTime,
})),
}, null, 2),
}],
};
}
);
server.tool(
'disconnect_participant',
'Forcibly disconnect a participant from an IVS real-time stage',
{
stageArn: z.string().startsWith('arn:aws:ivs:').describe('IVS stage ARN'),
participantId: z.string().describe('IVS participant ID (from list_stage_participants, not userId)'),
reason: z.string().max(128).optional().describe('Reason shown in client SDK disconnect callback'),
},
async ({ stageArn, participantId, reason }) => {
await ivsRt.send(new DisconnectParticipantCommand({ stageArn, participantId, reason }));
return { content: [{ type: 'text', text: `Participant ${participantId} disconnected` }] };
}
);
server.tool(
'delete_stage',
'Delete an IVS real-time stage (removes the room permanently)',
{
stageArn: z.string().startsWith('arn:aws:ivs:').describe('IVS stage ARN'),
},
async ({ stageArn }) => {
await ivsRt.send(new DeleteStageCommand({ arn: stageArn }));
return { content: [{ type: 'text', text: `Stage ${stageArn} deleted` }] };
}
);
const transport = new StdioServerTransport();
await server.connect(transport);
Production gotchas
| Gotcha | Symptom | Fix |
|---|---|---|
| Wrong SDK package | IvsClient from client-ivs has no stage commands; CreateStage undefined |
Import from @aws-sdk/client-ivs-realtime, not @aws-sdk/client-ivs |
| Using userId to disconnect | DisconnectParticipant throws ResourceNotFoundException |
Use participantId from ListParticipants, not the application userId |
| No active session on empty stage | ListParticipants throws ResourceNotFoundException if sessionId is from ended session |
Filter sessions by !endTime; return empty list if no active session |
| Token expiry not handled on client | Participant silently loses ability to send/receive at token expiry | Client SDK fires token-expiring callback at 30 s before expiry — use it to fetch a new token |
| Reconnect generates new participantId | Stale participant IDs in MCP server cache cause disconnect failures | Always fetch current participantId from ListParticipants before DisconnectParticipant |
| Max 12 publishers per stage | 13th PUBLISH token join attempt fails at WebRTC negotiation, not at token creation |
Check ListParticipants filterByPublished=true count before issuing PUBLISH tokens; cap at 12 |
| Attributes 1 KB limit | 400 Bad Request from CreateParticipantToken with large attribute map |
Keep token attributes minimal; large metadata belongs in your application database keyed by userId |
| Stage not deleted after session ends | Idle stages accumulate; no cost but ARN namespace clutters | Delete ephemeral stages on IVS Stage Session Ended EventBridge event |
Related pages
- Amazon IVS for MCP servers — channels, stream keys, and timed metadata
- IVS recording to S3 — auto-record configuration, thumbnails, and EventBridge events
- IVS Chat — chat rooms, server-side events, and user moderation
- Amazon Kinesis Video Streams for MCP servers
- Webhook-based event handling for MCP servers