Guide · Amazon Kinesis Video Streams · Archived Media & Frame Extraction
Kinesis Video Streams Archived Media for MCP Servers — HLS, DASH, and Frame Extraction for AI Pipelines
KVS archived media APIs let your MCP server retrieve stored video from any point in the retention window — whether to generate a time-limited HLS/DASH URL for human review, or to pull raw MKV fragment data for AI frame extraction. The key distinction is purpose: HLS/DASH URLs are for human playback (video player in a browser); GetMediaForFragmentList + ListFragments are for machine consumption — giving you the raw binary data to pipe through ffmpeg or a frame decoder to feed individual JPEG frames into Claude Vision, Rekognition, or any image model.
TL;DR
All archived media APIs require calling GetDataEndpointCommand first (see KVS overview) and then constructing a KinesisVideoArchivedMediaClient with that endpoint. Use HLS (GetHLSStreamingSessionURLCommand) or DASH (GetDASHStreamingSessionURLCommand) for human-viewable playback URLs. Use ListFragments + GetMediaForFragmentList for AI frame extraction pipelines. The stream must have DataRetentionInHours >= 1 for any archived media to exist. Fragment timing is queryable by SERVER_TIMESTAMP (more reliable for drift-prone devices) or PRODUCER_TIMESTAMP.
Client setup: the data endpoint requirement
All archived media operations target a stream-specific endpoint, not the standard KVS regional endpoint. Set up two clients — one for the control plane (GetDataEndpoint), one for media operations:
import { KinesisVideoClient, GetDataEndpointCommand } from "@aws-sdk/client-kinesis-video";
import {
KinesisVideoArchivedMediaClient,
GetHLSStreamingSessionURLCommand,
GetDASHStreamingSessionURLCommand,
ListFragmentsCommand,
GetMediaForFragmentListCommand,
} from "@aws-sdk/client-kinesis-video-archived-media";
const kv = new KinesisVideoClient({ region: "us-east-1" });
const STREAM_NAME = "factory-cam-01";
// Cache this endpoint per stream — it doesn't change unless the stream is recreated
async function getArchivedMediaClient(streamName, apiName) {
const { DataEndpoint } = await kv.send(new GetDataEndpointCommand({
StreamName: streamName,
APIName: apiName,
}));
return new KinesisVideoArchivedMediaClient({
region: "us-east-1",
endpoint: DataEndpoint,
});
}
// One client per API name (each may return a different endpoint)
const hlsClient = await getArchivedMediaClient(STREAM_NAME, "GET_HLS_STREAMING_SESSION_URL");
const dashClient = await getArchivedMediaClient(STREAM_NAME, "GET_DASH_STREAMING_SESSION_URL");
const listClient = await getArchivedMediaClient(STREAM_NAME, "LIST_FRAGMENTS");
const getMfflClient = await getArchivedMediaClient(STREAM_NAME, "GET_MEDIA_FOR_FRAGMENT_LIST");
HLS streaming session URLs
GetHLSStreamingSessionURLCommand returns a time-limited URL that any HLS-compatible player (hls.js, Video.js, Safari native, AWS Elemental MediaPlayer) can use to play back video. The URL expires between 5 and 43,200 seconds (default 300 seconds):
// ON_DEMAND: play a specific time window (great for incident review)
const { HLSStreamingSessionURL: onDemandUrl } = await hlsClient.send(
new GetHLSStreamingSessionURLCommand({
StreamName: STREAM_NAME,
PlaybackMode: "ON_DEMAND",
HLSFragmentSelector: {
FragmentSelectorType: "SERVER_TIMESTAMP",
TimestampRange: {
StartTimestamp: new Date("2026-11-17T10:00:00Z"),
EndTimestamp: new Date("2026-11-17T10:05:00Z"),
},
},
ContainerFormat: "FRAGMENTED_MP4", // "FRAGMENTED_MP4" or "MPEG_TS"
DisplayFragmentTimestamp: "ALWAYS", // "ALWAYS" or "NEVER"
DisplayFragmentNumber: "NEVER",
MaxMediaPlaylistFragmentResults: 1000,
Expires: 3600, // seconds
})
);
console.log("HLS on-demand URL:", onDemandUrl);
// LIVE: play from ~5 seconds behind the live edge (rolling window)
const { HLSStreamingSessionURL: liveUrl } = await hlsClient.send(
new GetHLSStreamingSessionURLCommand({
StreamName: STREAM_NAME,
PlaybackMode: "LIVE",
HLSFragmentSelector: {
FragmentSelectorType: "SERVER_TIMESTAMP",
},
Expires: 3600,
})
);
// LIVE_REPLAY: start at a past timestamp and play forward to live
const { HLSStreamingSessionURL: replayUrl } = await hlsClient.send(
new GetHLSStreamingSessionURLCommand({
StreamName: STREAM_NAME,
PlaybackMode: "LIVE_REPLAY",
HLSFragmentSelector: {
FragmentSelectorType: "SERVER_TIMESTAMP",
TimestampRange: {
StartTimestamp: new Date(Date.now() - 30 * 60 * 1000), // 30 minutes ago
},
},
Expires: 7200,
})
);
Key considerations for HLS URLs in MCP server responses:
- URL expiry vs session duration: The
Expiresvalue controls how long the URL itself is valid. Once a player opens the URL and starts downloading segments, the session persists even if the URL expires — the HLS playlist can be fetched once and the segments downloaded over a longer window. SetExpiresgenerously for human-review workflows. - FRAGMENTED_MP4 vs MPEG_TS: FRAGMENTED_MP4 (fMP4) is the modern format, compatible with all current players and required for CMAF delivery. MPEG_TS is the legacy format needed for older players or Apple HLS in Safari on older iOS. Default to FRAGMENTED_MP4.
- H.264 and H.265 requirement: HLS URLs only work for streams that contain H.264 (AVC) or H.265 (HEVC) encoded video. Raw YUV, MJPEG, or other formats require transcoding before ingestion for HLS playback to work.
DASH streaming session URLs
DASH (Dynamic Adaptive Streaming over HTTP / MPEG-DASH) is an alternative to HLS, preferred in some enterprise and Android contexts. The API is nearly identical:
const { DASHStreamingSessionURL } = await dashClient.send(
new GetDASHStreamingSessionURLCommand({
StreamName: STREAM_NAME,
PlaybackMode: "ON_DEMAND",
DASHFragmentSelector: {
FragmentSelectorType: "SERVER_TIMESTAMP",
TimestampRange: {
StartTimestamp: new Date("2026-11-17T10:00:00Z"),
EndTimestamp: new Date("2026-11-17T10:05:00Z"),
},
},
DisplayFragmentTimestamp: "ALWAYS",
DisplayFragmentNumber: "NEVER",
MaxManifestFragmentResults: 1000,
Expires: 3600,
})
);
console.log("DASH URL:", DASHStreamingSessionURL);
DASH URLs are compatible with dash.js, Shaka Player, and ExoPlayer (Android). For MCP server APIs that return video URLs, consider returning both HLS and DASH to maximize client compatibility — the incremental cost is two GetDataEndpoint calls plus two session URL calls.
Listing fragments for time-range queries
ListFragmentsCommand is the index lookup for archived media — it returns fragment metadata (fragment numbers, timestamps, durations, sizes) without returning media bytes. Use it to discover which fragments exist in a time window before deciding whether to fetch them:
const startTime = new Date("2026-11-17T10:00:00Z");
const endTime = new Date("2026-11-17T10:01:00Z"); // 1-minute window
const fragmentNumbers = [];
let nextToken;
do {
const response = await listClient.send(new ListFragmentsCommand({
StreamName: STREAM_NAME,
MaxResults: 100,
NextToken: nextToken,
FragmentSelector: {
FragmentSelectorType: "SERVER_TIMESTAMP",
TimestampRange: {
StartTimestamp: startTime,
EndTimestamp: endTime,
},
},
}));
for (const fragment of response.Fragments ?? []) {
fragmentNumbers.push(fragment.FragmentNumber);
console.log(
"Fragment:", fragment.FragmentNumber,
"| Start:", fragment.ProducerTimestamp?.toISOString(),
"| Duration:", fragment.FragmentLengthInMilliseconds, "ms",
"| Size:", fragment.FragmentSizeInBytes, "bytes"
);
}
nextToken = response.NextToken;
} while (nextToken);
console.log(`Found ${fragmentNumbers.length} fragments in the 1-minute window`);
Fragment metadata fields: FragmentNumber (monotonically increasing string, used for retrieval), ProducerTimestamp (device clock), ServerTimestamp (KVS receipt time), FragmentLengthInMilliseconds (typical: 2000ms for 2fps cameras, 500ms for 30fps), FragmentSizeInBytes.
AI frame extraction with GetMediaForFragmentList
This is the core API for feeding video frames into AI models. GetMediaForFragmentListCommand returns the raw MKV container bytes for a list of fragment numbers. You then pipe the MKV binary through a frame decoder (ffmpeg, fluent-ffmpeg, or a pure-JS MKV parser) to extract individual frames as JPEG or PNG:
import { createWriteStream, mkdirSync } from "fs";
import { join } from "path";
import { spawn } from "child_process";
import { Readable } from "stream";
async function extractFramesFromFragments(fragmentNumbers, outputDir) {
mkdirSync(outputDir, { recursive: true });
// Retrieve raw MKV bytes for the specified fragments
const response = await getMfflClient.send(new GetMediaForFragmentListCommand({
StreamName: STREAM_NAME,
Fragments: fragmentNumbers, // array of fragment number strings, max 1000
}));
// response.Payload is a ReadableStream (browser) or Node.js Readable
const mkvStream = response.Payload;
// Pipe through ffmpeg to extract JPEG frames at 1fps
return new Promise((resolve, reject) => {
const ffmpeg = spawn("ffmpeg", [
"-i", "pipe:0", // read MKV from stdin
"-vf", "fps=1", // extract 1 frame per second
"-q:v", "2", // JPEG quality (2 = high quality, 31 = low)
join(outputDir, "frame-%04d.jpg"), // output pattern
"-y", // overwrite existing files
], { stdio: ["pipe", "pipe", "pipe"] });
// Connect MKV stream to ffmpeg stdin
if (mkvStream instanceof Readable) {
mkvStream.pipe(ffmpeg.stdin);
} else {
// For browser ReadableStream:
const nodeStream = Readable.fromWeb(mkvStream);
nodeStream.pipe(ffmpeg.stdin);
}
const frames = [];
ffmpeg.stdout.on("data", (chunk) => frames.push(chunk));
ffmpeg.on("close", (code) => {
if (code === 0) {
resolve(outputDir);
} else {
reject(new Error(`ffmpeg exited with code ${code}`));
}
});
ffmpeg.stderr.on("data", (data) => {
// ffmpeg logs to stderr normally — only log errors
const msg = data.toString();
if (msg.includes("Error")) console.error("[ffmpeg]", msg);
});
});
}
// Usage: extract frames from the fragments we listed above
const framesDir = await extractFramesFromFragments(fragmentNumbers, "/tmp/kvs-frames");
console.log("Frames extracted to:", framesDir);
Sending extracted frames to Claude Vision
Once you have JPEG frames on disk or in memory, pass them to Claude as base64-encoded image blocks in an MCP tool response:
import { readFileSync, readdirSync } from "fs";
import { join } from "path";
import Anthropic from "@anthropic-ai/sdk";
async function analyzeFramesWithClaude(framesDir, question) {
const client = new Anthropic();
// Read up to 10 frames (Claude supports up to 20 images per message)
const frameFiles = readdirSync(framesDir)
.filter(f => f.endsWith(".jpg"))
.sort()
.slice(0, 10);
const imageBlocks = frameFiles.map(filename => ({
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: readFileSync(join(framesDir, filename)).toString("base64"),
},
}));
const response = await client.messages.create({
model: "claude-opus-4-7",
max_tokens: 1024,
messages: [{
role: "user",
content: [
...imageBlocks,
{
type: "text",
text: question,
},
],
}],
});
return response.content[0].text;
}
const analysis = await analyzeFramesWithClaude(
framesDir,
"Describe what you see in these frames. Is there any safety concern visible?"
);
console.log("Claude analysis:", analysis);
Live GetMedia for real-time frame tapping
GetMedia streams live video as a continuous chunked MKV response. Unlike HLS/DASH which buffer segments, GetMedia delivers fragments as they arrive — useful when you need sub-second latency for real-time analysis without WebRTC setup:
import { KinesisVideoMediaClient, GetMediaCommand } from "@aws-sdk/client-kinesis-video-media";
const { DataEndpoint: mediaEndpoint } = await kv.send(new GetDataEndpointCommand({
StreamName: STREAM_NAME,
APIName: "GET_MEDIA",
}));
const kvMedia = new KinesisVideoMediaClient({
region: "us-east-1",
endpoint: mediaEndpoint,
});
const { Payload } = await kvMedia.send(new GetMediaCommand({
StreamName: STREAM_NAME,
StartSelector: {
StartSelectorType: "NOW", // or "EARLIEST", "FRAGMENT_NUMBER", "SERVER_TIMESTAMP", "PRODUCER_TIMESTAMP", "CONTINUATION_TOKEN"
},
}));
// Payload is a live ReadableStream — consume with a timeout
const readable = Readable.fromWeb(Payload);
// Collect 10 seconds of data, then close
const chunks = [];
const timeout = setTimeout(() => readable.destroy(), 10_000);
readable.on("data", chunk => chunks.push(chunk));
readable.on("end", () => {
clearTimeout(timeout);
const mkvBuffer = Buffer.concat(chunks);
console.log("Captured", mkvBuffer.length, "bytes of live MKV");
// Now pipe mkvBuffer through ffmpeg for frame extraction
});
Use StartSelectorType: "CONTINUATION_TOKEN" to resume a GetMedia stream from where you left off if your consumer disconnects and reconnects — the continuation token is returned in the MKV stream header metadata.
Key gotchas
- Fragment arrival lag for ON_DEMAND: Fragments appear in the index 2–5 seconds after they are received by KVS. When querying a time range that extends to "just now" with ON_DEMAND mode, back off the end timestamp by 10 seconds to avoid missing the most recent fragments.
- GetMediaForFragmentList max 1,000 fragments per call: If your time range spans more than ~1,000 fragments (1 fragment per 2 seconds = ~33 minutes), you must split into multiple calls. Use
ListFragmentsfirst to get fragment numbers, then batch them into calls of 1,000. - MKV requires a valid header to decode: The MKV binary from
GetMediaForFragmentListstarts with a valid EBML header. ffmpeg handles this correctly, but custom parsers must handle multi-fragment MKV streams (each fragment is a Cluster element within the same MKV stream, not a separate file). - Payload stream must be consumed: If you call
GetMediaForFragmentListand don't consume the entirePayloadstream, the HTTP connection stays open and counts against your connection limits. Always pipe the entire stream to its destination or explicitly destroy it. - Producer vs server timestamp consistency: Always choose one selector type and stick with it. Mixing
SERVER_TIMESTAMPinListFragmentswithPRODUCER_TIMESTAMPinGetMediaForFragmentListcan result in gaps or overlaps if the device clock has drift relative to server time.
Continue in this series
- KVS SDK overview and stream management — CreateStream, GetDataEndpoint, data endpoint pattern, retention configuration
- WebRTC signaling channels — CreateSignalingChannel, GetSignalingChannelEndpoint, GetIceServerConfig, real-time video
- Rekognition stream processor integration — CreateStreamProcessorCommand, ConnectedHome vs FaceSearch, event-driven AI analysis
Related AWS AI and media guides: Rekognition labels for MCP servers · Amazon Bedrock for MCP servers · Kinesis Data Streams for MCP servers