Guide · Amazon IVS · Live Channels, Stream Keys & Timed Metadata
Amazon IVS for MCP Servers — Live Streaming Channels, Stream Keys, and Real-Time Metadata
Amazon Interactive Video Service exposes a management API — @aws-sdk/client-ivs — that lets MCP server tools create and control live streaming channels, retrieve RTMPS ingest endpoints and stream keys, inject timed metadata into active streams, and read real-time stream health metrics. AI agents built on top of IVS can automate moderation tasks, trigger in-stream overlays and polls, monitor stream quality, and react to viewer counts — all through typed MCP tool handlers that wrap IVS API commands. This guide covers the full integration path: channel types and their latency tradeoffs, stream key lifecycle, the PutMetadata timed-metadata mechanism, GetStream health polling, and the production gotchas that cause silent ingest failures and metadata delivery errors.
TL;DR
Use @aws-sdk/client-ivs for channel management, stream key retrieval, metadata injection, and stream health. Channel type controls latency: STANDARD gives sub-two-second latency, ADVANCED_HD and ADVANCED_SD add transcoding ladder options, BASIC is passthrough-only. Stream keys are credentials — treat them like passwords and retrieve them once to store in Secrets Manager. PutMetadata delivers arbitrary string payloads to IVS players as timed metadata events; the payload must be under 1 KB and delivery is best-effort (not guaranteed). GetStream returns health (HEALTHY, STARVING, or UNKNOWN), viewerCount, and startTime — poll it on a 30-second interval for dashboards. A channel with no active ingest returns a ChannelNotBroadcasting error from GetStream — handle this as a normal state, not an error that requires retry.
Why IVS in an MCP server
Live streaming platforms — educational tools, gaming, virtual events, e-commerce live shows — increasingly use AI agents to automate tasks that previously required human operators. An IVS-backed MCP server gives an AI agent the primitives to: check whether a scheduled stream is live, inject a poll overlay at a specific moment, disconnect a banned viewer, trigger a highlight clip, or alert a human operator when stream health degrades. Without the MCP abstraction, each of these requires direct SDK integration in the agent's runtime; wrapping IVS in an MCP server exposes them as named tools the agent can discover and call with structured arguments.
IVS is also architecturally simpler than self-hosted video infrastructure. There is no media server to manage, no CDN origin to configure, and no transcoding pipeline to operate. A channel ARN, an ingest endpoint, and a stream key are all you need to accept RTMPS input from OBS or a custom encoder. The API surface is narrow enough that a single MCP server can expose the entire IVS control plane as a dozen well-named tools — something impractical with a full-featured media server like Wowza or Nimble.
The IVS management API is regional. All channel ARNs, stream keys, and recording configurations are scoped to a single AWS region, and the RTMPS ingest endpoints embed the region in their hostname (a1b2c3d4e5f6.global-contribute.live-video.net resolves to a regional POP, but the channel ARN and all API calls must use the same region). Multi-region architectures require separate channels per region and a routing layer outside IVS itself.
SDK installation and client setup
IVS uses a single SDK package for the standard live streaming API. The IVS real-time stages API and the IVS chat API are separate packages with separate clients — this guide covers the core streaming API only.
npm install @aws-sdk/client-ivs
Instantiate the client once per MCP server process and reuse it across tool calls. The IVS API is available in us-east-1, us-west-2, eu-west-1, and ap-northeast-1 — verify current availability in the IVS pricing page before deploying to other regions.
import { IvsClient } from '@aws-sdk/client-ivs';
const ivs = new IvsClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
IAM permissions needed for the core management operations are ivs:CreateChannel, ivs:GetChannel, ivs:UpdateChannel, ivs:DeleteChannel, ivs:CreateStreamKey, ivs:GetStreamKey, ivs:DeleteStreamKey, ivs:GetStream, ivs:ListStreams, ivs:StopStream, and ivs:PutMetadata. Use a least-privilege policy that grants only the operations your MCP server exposes as tools — a read-only monitoring server does not need CreateChannel or PutMetadata.
Channel types and latency tradeoffs
IVS channel type determines ingest protocol support, transcoding ladder, and viewer latency. Choose the type at channel creation; changing it later requires updating the channel and stopping any active stream first.
| Type | Latency | Max resolution | Transcoding | Use case |
|---|---|---|---|---|
STANDARD | ~2–5 s | 1080p60 | Multi-rendition | Gaming, interactive events requiring low latency |
ADVANCED_SD | ~2–5 s | 480p30 | Multi-rendition + B-frames | Mobile-first, bandwidth-constrained viewers |
ADVANCED_HD | ~2–5 s | 1080p60 | Multi-rendition + B-frames | High-motion content, e-sports |
BASIC | ~2–5 s | 1080p | Passthrough only | Low-cost educational content, controlled viewer environments |
STANDARD and the ADVANCED_* types perform server-side transcoding, producing a multi-bitrate HLS ladder that IVS players use for adaptive bitrate switching. BASIC passes the ingest stream through without transcoding — viewers receive only the resolution and bitrate the broadcaster sends. Use BASIC only when all viewers have reliable, high-bandwidth connections; adaptive bitrate is unavailable and stream quality degrades directly with network conditions.
ADVANCED_HD and ADVANCED_SD differ from STANDARD in that they encode B-frames, improving compression efficiency for high-motion content by approximately 20–30 percent at the same visual quality. The tradeoff is slightly higher encoding CPU on the ingest side. For MCP server tool arguments, expose channel type as an enum parameter with a default of STANDARD.
Creating a channel and retrieving the ingest endpoint
CreateChannelCommand returns both the channel resource and a default stream key in a single response. The stream key value is returned only on creation and is never returned again by the API — if you need it later, you must call GetStreamKeyCommand, but that command returns metadata only (not the key value). To retrieve the secret key value after initial creation, you must call CreateStreamKeyCommand to generate a new key (the old one continues to work until deleted) or store the initial value in Secrets Manager immediately after channel creation.
import {
IvsClient,
CreateChannelCommand,
type CreateChannelCommandInput,
type Channel,
type StreamKey
} from '@aws-sdk/client-ivs';
const ivs = new IvsClient({ region: 'us-east-1' });
async function createChannel(params: {
name: string;
type?: 'STANDARD' | 'ADVANCED_SD' | 'ADVANCED_HD' | 'BASIC';
latencyMode?: 'LOW' | 'NORMAL';
authorized?: boolean;
insecureIngest?: boolean;
recordingConfigurationArn?: string;
tags?: Record<string, string>;
}): Promise<{ channel: Channel; streamKey: StreamKey }> {
const input: CreateChannelCommandInput = {
name: params.name,
type: params.type ?? 'STANDARD',
latencyMode: params.latencyMode ?? 'LOW',
authorized: params.authorized ?? false,
insecureIngest: params.insecureIngest ?? false,
...(params.recordingConfigurationArn && {
recordingConfigurationArn: params.recordingConfigurationArn,
}),
tags: params.tags ?? {},
};
const response = await ivs.send(new CreateChannelCommand(input));
if (!response.channel || !response.streamKey) {
throw new Error('CreateChannel response missing channel or streamKey');
}
return {
channel: response.channel,
streamKey: response.streamKey,
};
}
The response channel.ingestEndpoint is the RTMPS hostname (e.g., a1b2c3d4e5f6.global-contribute.live-video.net). The broadcaster's OBS or encoder settings use rtmps://<ingestEndpoint>:443/app/ as the server URL and the stream key value as the stream key. The channel.playbackUrl is the HLS manifest URL viewers load in the IVS player or any HLS-capable player (https://a1b2c3d4e5f6.us-east-1.playback.live-video.net/api/video/v1/us-east-1/123456789012/channel/AbCdEfGhIjKl/index.m3u8).
The authorized flag controls whether the channel requires a playback authorization token for viewers. When authorized: true, viewers must present a signed JWT created with a signing key pair configured on the channel — this is distinct from the ingest stream key. For MCP servers that only control the production side, leave authorized: false unless your platform requires viewer authentication.
The insecureIngest flag allows RTMP (non-TLS) ingest on port 1935. Disable it in production — RTMPS on port 443 is the default and required for secure credential handling.
Stream key lifecycle and Secrets Manager storage
Stream keys are long-lived credentials that authenticate an RTMPS ingest connection to a specific channel. Each channel can have up to five stream keys. The key value is returned only by CreateStreamKeyCommand and during channel creation — there is no API to retrieve the secret value of an existing key. This means your MCP server must store stream key values in Secrets Manager (or SSM Parameter Store with SecureString) immediately after creation.
import {
IvsClient,
CreateStreamKeyCommand,
DeleteStreamKeyCommand,
ListStreamKeysCommand,
type StreamKey
} from '@aws-sdk/client-ivs';
import {
SecretsManagerClient,
CreateSecretCommand,
PutSecretValueCommand
} from '@aws-sdk/client-secrets-manager';
const ivs = new IvsClient({ region: 'us-east-1' });
const secrets = new SecretsManagerClient({ region: 'us-east-1' });
async function rotateStreamKey(channelArn: string): Promise<StreamKey> {
// Create new key first so channel never has zero active keys
const { streamKey } = await ivs.send(new CreateStreamKeyCommand({
channelArn,
tags: { rotatedAt: new Date().toISOString() },
}));
if (!streamKey?.value || !streamKey.arn) {
throw new Error('CreateStreamKey returned no value');
}
// Store in Secrets Manager immediately — value not retrievable later
const secretName = `ivs/stream-key/${streamKey.arn.split('/').pop()}`;
try {
await secrets.send(new CreateSecretCommand({
Name: secretName,
SecretString: JSON.stringify({
channelArn,
streamKeyArn: streamKey.arn,
value: streamKey.value,
createdAt: new Date().toISOString(),
}),
}));
} catch (err: unknown) {
if ((err as { name?: string }).name === 'ResourceExistsException') {
await secrets.send(new PutSecretValueCommand({
SecretId: secretName,
SecretString: JSON.stringify({
channelArn,
streamKeyArn: streamKey.arn,
value: streamKey.value,
rotatedAt: new Date().toISOString(),
}),
}));
} else {
throw err;
}
}
return streamKey;
}
async function listStreamKeys(channelArn: string): Promise<Array<{ arn: string; tags?: Record<string, string> }>> {
const response = await ivs.send(new ListStreamKeysCommand({ channelArn }));
return (response.streamKeys ?? []).map(k => ({
arn: k.arn ?? '',
tags: k.tags,
}));
}
When rotating stream keys, always create the new key before deleting the old one. Broadcasters using the old key continue to stream until their encoder reconnects — deleting the old key while a stream is active forces an immediate disconnect on the next reconnect attempt, not mid-stream. If you need to force immediate ingest termination, use StopStreamCommand instead.
Monitoring stream health with GetStream
GetStreamCommand returns the current stream state for a live channel. The response includes health, viewerCount, startTime, and streamId. If no broadcaster is connected to the channel, the command throws a ChannelNotBroadcasting exception — this is a normal channel state, not a service error. Your MCP tool handler must catch it and return a structured "not live" response rather than surfacing a 500 error to the agent.
import {
IvsClient,
GetStreamCommand,
ListStreamsCommand,
StopStreamCommand,
type Stream
} from '@aws-sdk/client-ivs';
const ivs = new IvsClient({ region: 'us-east-1' });
type StreamStatus =
| { live: true; health: string; viewerCount: number; startTime: Date; streamId: string }
| { live: false };
async function getStreamStatus(channelArn: string): Promise<StreamStatus> {
try {
const { stream } = await ivs.send(new GetStreamCommand({ channelArn }));
if (!stream) return { live: false };
return {
live: true,
health: stream.health ?? 'UNKNOWN',
viewerCount: stream.viewerCount ?? 0,
startTime: stream.startTime ?? new Date(0),
streamId: stream.streamId ?? '',
};
} catch (err: unknown) {
if ((err as { name?: string }).name === 'ChannelNotBroadcasting') {
return { live: false };
}
throw err;
}
}
async function listAllActiveStreams(): Promise<Stream[]> {
const streams: Stream[] = [];
let nextToken: string | undefined;
do {
const response = await ivs.send(new ListStreamsCommand({
nextToken,
filterBy: { health: 'STARVING' }, // filter to only degraded streams
}));
streams.push(...(response.streams ?? []));
nextToken = response.nextToken;
} while (nextToken);
return streams;
}
async function stopStream(channelArn: string): Promise<void> {
await ivs.send(new StopStreamCommand({ channelArn }));
}
The health field has three values. HEALTHY means the ingest bitrate and frame rate are within expected ranges. STARVING means the ingest bitrate has dropped below the transcoder's minimum threshold — typically caused by network congestion on the broadcaster's upload path. UNKNOWN is returned during the first several seconds of a new stream before enough data has accumulated for the health classifier. Poll GetStream on a 30-second interval for dashboards; more frequent polling is not useful because the health metric is updated on a 10–15 second rolling window.
The ListStreamsCommand filterBy.health parameter accepts HEALTHY or STARVING — it does not accept UNKNOWN. For a "show me all degraded streams" monitoring tool, filter by STARVING. For a "show me all live channels" dashboard, omit the filter and paginate through all results. ListStreams only returns channels that currently have an active ingest — channels with no broadcaster are not included regardless of filter.
Sending timed metadata with PutMetadata
PutMetadataCommand injects an arbitrary string payload into the active live stream. Players using the Amazon IVS player SDK receive the payload as a timed metadata event synchronized to the video timeline at the moment of injection. The payload is typically a JSON string — a poll question, a product SKU for a shopping overlay, a quiz answer reveal, or a moderation event that triggers a client-side UI action.
import {
IvsClient,
PutMetadataCommand
} from '@aws-sdk/client-ivs';
const ivs = new IvsClient({ region: 'us-east-1' });
type MetadataPayload =
| { type: 'poll'; question: string; options: string[]; durationSeconds: number }
| { type: 'product'; sku: string; name: string; price: number; url: string }
| { type: 'quiz'; question: string; correctIndex: number; revealAt: number }
| { type: 'moderation'; action: 'warn' | 'mute'; targetUserId: string }
| { type: 'custom'; data: unknown };
async function sendMetadata(
channelArn: string,
payload: MetadataPayload
): Promise<void> {
const serialized = JSON.stringify(payload);
if (Buffer.byteLength(serialized, 'utf8') > 1024) {
throw new Error(
`Metadata payload ${Buffer.byteLength(serialized, 'utf8')} bytes exceeds 1 KB limit`
);
}
try {
await ivs.send(new PutMetadataCommand({
channelArn,
metadata: serialized,
}));
} catch (err: unknown) {
if ((err as { name?: string }).name === 'ChannelNotBroadcasting') {
throw new Error('Cannot send metadata: channel is not currently live');
}
throw err;
}
}
Metadata delivery is best-effort. The IVS service inserts the payload into the stream at the current segment boundary, which introduces a timing jitter of up to one HLS segment duration (typically 2 seconds). If the network between IVS and a viewer drops segments, the metadata event is lost — there is no replay or guaranteed delivery. For interactions where the player must receive a specific event (such as a quiz reveal that all viewers must see), use a WebSocket or server-sent events channel alongside IVS rather than relying solely on PutMetadata.
The 1 KB payload limit is a hard constraint enforced by the API — the request returns a 400 error if exceeded. For larger payloads (product catalogs, quiz banks), store data in a CDN-hosted JSON file and send only a reference ID as the metadata payload; the player fetches the full data from the CDN on receipt of the metadata event.
PutMetadata throws ChannelNotBroadcasting if the channel has no active ingest, the same as GetStream. Build a standard retry pattern: check stream status, then send metadata only if live. Do not retry PutMetadata on ChannelNotBroadcasting — the error will not resolve until a broadcaster connects.
MCP tool handler: full channel management server
The following MCP server exposes five IVS tools: create a channel, get stream status, send metadata to a live stream, stop a stream, and list all active streams. Each tool is typed with Zod to validate arguments before they reach the AWS API.
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
IvsClient,
CreateChannelCommand,
GetStreamCommand,
PutMetadataCommand,
StopStreamCommand,
ListStreamsCommand
} from '@aws-sdk/client-ivs';
import { z } from 'zod';
const ivs = new IvsClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const server = new McpServer({ name: 'ivs-manager', version: '1.0.0' });
server.tool(
'create_channel',
'Create an IVS live streaming channel and return ingest endpoint, playback URL, and stream key ARN',
{
name: z.string().min(1).max(128).describe('Channel name (shown in AWS console)'),
type: z.enum(['STANDARD', 'ADVANCED_SD', 'ADVANCED_HD', 'BASIC']).default('STANDARD'),
latencyMode: z.enum(['LOW', 'NORMAL']).default('LOW'),
},
async ({ name, type, latencyMode }) => {
const { channel, streamKey } = await ivs.send(new CreateChannelCommand({
name, type, latencyMode, authorized: false,
}));
return {
content: [{
type: 'text',
text: JSON.stringify({
channelArn: channel?.arn,
ingestEndpoint: channel?.ingestEndpoint,
playbackUrl: channel?.playbackUrl,
streamKeyArn: streamKey?.arn,
streamKeyValue: streamKey?.value, // store immediately — not retrievable later
type, latencyMode,
}, null, 2),
}],
};
}
);
server.tool(
'get_stream_status',
'Get the current live stream status for an IVS channel — viewer count, health, and start time',
{
channelArn: z.string().startsWith('arn:aws:ivs:').describe('IVS channel ARN'),
},
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 an active IVS live stream (polls, products, quiz events)',
{
channelArn: z.string().startsWith('arn:aws:ivs:').describe('IVS channel ARN'),
payload: z.record(z.unknown()).describe('JSON payload to deliver to players (must be under 1 KB serialized)'),
},
async ({ channelArn, payload }) => {
const serialized = JSON.stringify(payload);
const bytes = Buffer.byteLength(serialized, 'utf8');
if (bytes > 1024) {
return {
content: [{ type: 'text', text: `Error: payload is ${bytes} bytes, exceeds 1024 byte limit` }],
isError: true,
};
}
try {
await ivs.send(new PutMetadataCommand({ channelArn, metadata: serialized }));
return { content: [{ type: 'text', text: `Metadata sent (${bytes} bytes)` }] };
} 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_stream',
'Terminate an active IVS live stream (disconnects the broadcaster)',
{
channelArn: z.string().startsWith('arn:aws:ivs:').describe('IVS channel ARN'),
},
async ({ channelArn }) => {
await ivs.send(new StopStreamCommand({ channelArn }));
return { content: [{ type: 'text', text: 'Stream stopped' }] };
}
);
server.tool(
'list_active_streams',
'List all currently live IVS channels, optionally filtered to degraded streams only',
{
degradedOnly: z.boolean().default(false).describe('Filter to STARVING streams only'),
},
async ({ degradedOnly }) => {
const streams = [];
let nextToken: string | undefined;
do {
const response = await ivs.send(new ListStreamsCommand({
nextToken,
...(degradedOnly ? { 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);
Production gotchas
| Gotcha | Symptom | Fix |
|---|---|---|
| Stream key value not stored after creation | GetStreamKey returns metadata but not the secret value; broadcaster cannot ingest |
Store streamKey.value to Secrets Manager immediately after CreateChannel or CreateStreamKey |
ChannelNotBroadcasting treated as error |
MCP tool crashes when polling an idle channel | Catch by name and return { live: false } — it is a normal state |
| Metadata payload over 1 KB | 400 Bad Request from PutMetadata |
Serialize and measure bytes before sending; use CDN references for large payloads |
| Wrong region for channel ARN | ResourceNotFoundException on GetStream or PutMetadata |
IVS channel ARNs embed the region — use a client matching the ARN's region, not a fixed default |
| Stopping a stream disconnects the broadcaster | Broadcaster's OBS goes to "stream disconnected" state unexpectedly | StopStream is aggressive — confirm with the broadcaster or use PutMetadata for soft stop signals |
| Metadata delivery during segment boundary | Timed metadata arrives 2–3 seconds after PutMetadata call |
Send metadata 2–3 s before the intended trigger time; delivery is not instantaneous |
| BASIC channel with adaptive bitrate expectation | Viewers on mobile get buffer stalls on BASIC channels |
BASIC does no transcoding — use STANDARD or ADVANCED_* for mixed-connectivity audiences |
| Multi-region channel management | ListStreams only returns channels in one region |
Instantiate a separate IvsClient per region; fan out ListStreams calls and merge results |
Related pages
- IVS recording to S3 — auto-record configuration, thumbnails, and EventBridge events
- IVS real-time stages — WebRTC stages, participant tokens, and disconnect operations
- IVS Chat — chat rooms, server-side events, and user moderation tools
- Amazon Kinesis Video Streams for MCP servers
- Amazon MediaConvert for MCP servers — video transcoding jobs