Blog · Amazon Kinesis Video Streams · Production Guide

Amazon Kinesis Video Streams for MCP Servers: Five-Package SDK, AI Frame Extraction Pipeline, and Real-Time WebRTC Agents

Amazon Kinesis Video Streams (KVS) is the AWS-managed bridge between physical cameras and AI models. For MCP server teams building multi-modal agents, it solves a problem that S3 and standard streaming APIs cannot: securely ingesting, storing, and retrieving continuous video at scale so that agents can reach back in time, extract frames from a specific two-minute window, pipe them through ffmpeg, and feed individual JPEG stills into Claude Vision for analysis. This guide synthesises the full KVS stack — from the unusual five-package SDK split through the archived media frame extraction pipeline, WebRTC signaling for real-time agents, and Rekognition Stream Processors for event-driven video AI.

Why video access belongs in an MCP tool surface

Most MCP server toolboxes are text-and-data-centric: a tool fetches JSON from a database, calls an API, reads a file. Adding vision capabilities changes what an agent can reason about. Three use cases stand out for MCP teams:

All three patterns run on the same KVS infrastructure. What differs is the retrieval path: archived media APIs for retrospective access, live GetMedia for near-real-time frame capture, and Rekognition Stream Processors for event-driven delivery.

The five-package SDK split and what each package owns

Unlike nearly every other AWS service, KVS ships five separate npm packages. This is not an oversight — it reflects distinct interaction planes that have different endpoints, different IAM namespaces, and different billing models:

npm install \
  @aws-sdk/client-kinesis-video \
  @aws-sdk/client-kinesis-video-media \
  @aws-sdk/client-kinesis-video-archived-media \
  @aws-sdk/client-kinesis-video-signaling \
  @aws-sdk/client-kinesis-video-webrtc-storage
PackageWhat it doesKey commands
client-kinesis-videoControl plane: stream and signaling channel lifecycleCreateStreamCommand, GetDataEndpointCommand, CreateSignalingChannelCommand
client-kinesis-video-mediaLive stream: continuous chunked MKV deliveryGetMediaCommand
client-kinesis-video-archived-mediaArchived retrieval: HLS/DASH URLs and raw MKV fragmentsListFragmentsCommand, GetMediaForFragmentListCommand, GetHLSStreamingSessionURLCommand
client-kinesis-video-signalingWebRTC ICE server config: STUN/TURN credentialsGetIceServerConfigCommand
client-kinesis-video-webrtc-storageWebRTC + storage: simultaneous live feed and archivalJoinStorageSessionCommand

For AI frame extraction — the most common MCP use case — you need client-kinesis-video (for GetDataEndpointCommand) and client-kinesis-video-archived-media (for ListFragmentsCommand and GetMediaForFragmentListCommand). The signaling and media packages are only needed for real-time WebRTC pipelines.

See the KVS SDK overview guide for the full stream creation walkthrough, retention configuration, and IAM policy setup.

The data endpoint pattern: the invariant you can't skip

Every media operation in KVS — HLS streaming sessions, raw MKV fragment retrieval, live GetMedia, WebRTC ICE config — targets a stream-specific endpoint URL, not the standard regional endpoint. Using the default regional endpoint for media calls returns ResourceNotFoundException even if the stream exists and you have correct IAM permissions.

The pattern is always two steps:

import { KinesisVideoClient, GetDataEndpointCommand } from "@aws-sdk/client-kinesis-video";
import { KinesisVideoArchivedMediaClient } from "@aws-sdk/client-kinesis-video-archived-media";

const kv = new KinesisVideoClient({ region: "us-east-1" });

// Step 1: resolve the stream-specific endpoint for the API you want
const { DataEndpoint } = await kv.send(new GetDataEndpointCommand({
  StreamName: "factory-cam-01",
  APIName: "GET_MEDIA_FOR_FRAGMENT_LIST",
  // "LIST_FRAGMENTS" | "GET_MEDIA" | "GET_HLS_STREAMING_SESSION_URL"
  // "GET_DASH_STREAMING_SESSION_URL" | "JOIN_STORAGE_SESSION"
}));

// Step 2: instantiate the media client pointed at that endpoint
const kvArchived = new KinesisVideoArchivedMediaClient({
  region: "us-east-1",
  endpoint: DataEndpoint,  // e.g. "https://b-23456789.kinesisvideo.us-east-1.amazonaws.com"
});

Data endpoints are durable — they don't rotate unless a stream is deleted and recreated. Cache the endpoint per (stream name, API name) pair at the start of a session rather than re-fetching it on every tool call. Each API name may return a different endpoint URL, so the cache key must include both dimensions.

One critical nuance: each API name requires its own endpoint lookup. A client built from the LIST_FRAGMENTS endpoint cannot be used for GET_MEDIA_FOR_FRAGMENT_LIST calls. In practice this means your MCP tool initializer calls GetDataEndpointCommand twice — once per API — and builds two clients.

The AI frame extraction pipeline: ListFragments → GetMediaForFragmentList → ffmpeg → Claude Vision

This is the core pattern for any MCP tool that lets an agent inspect what a camera saw during a specific time window. The full pipeline has four stages:

Stage 1: Enumerate fragments in the time window

ListFragmentsCommand returns fragment metadata — fragment numbers, timestamps, durations — without returning video bytes. Use it to discover what exists before committing to a byte retrieval:

import { ListFragmentsCommand } from "@aws-sdk/client-kinesis-video-archived-media";

const listClient = new KinesisVideoArchivedMediaClient({
  region: "us-east-1",
  endpoint: await resolveEndpoint("factory-cam-01", "LIST_FRAGMENTS"),
});

const startTime = new Date("2026-11-17T10:00:00Z");
const endTime   = new Date("2026-11-17T10:02:00Z"); // 2-minute window

const fragmentNumbers = [];
let nextToken;

do {
  const response = await listClient.send(new ListFragmentsCommand({
    StreamName: "factory-cam-01",
    MaxResults: 100,
    NextToken: nextToken,
    FragmentSelector: {
      FragmentSelectorType: "SERVER_TIMESTAMP",  // more reliable than producer timestamp
      TimestampRange: { StartTimestamp: startTime, EndTimestamp: endTime },
    },
  }));

  for (const frag of response.Fragments ?? []) {
    fragmentNumbers.push(frag.FragmentNumber);
  }
  nextToken = response.NextToken;
} while (nextToken);

console.log(`Found ${fragmentNumbers.length} fragments`);

Use SERVER_TIMESTAMP rather than PRODUCER_TIMESTAMP when querying IoT device streams. Embedded devices — Raspberry Pi camera modules, industrial sensors, IP cameras — often have clock drift relative to wall time. KVS records both timestamps; the server timestamp is what KVS received the fragment, which is reliable. Producer timestamps from drift-prone devices can be minutes off.

Stage 2: Retrieve raw MKV bytes

GetMediaForFragmentListCommand returns the binary MKV container for a list of fragment numbers. Fragment numbers come directly from stage 1:

import { GetMediaForFragmentListCommand } from "@aws-sdk/client-kinesis-video-archived-media";

const getMfflClient = new KinesisVideoArchivedMediaClient({
  region: "us-east-1",
  endpoint: await resolveEndpoint("factory-cam-01", "GET_MEDIA_FOR_FRAGMENT_LIST"),
});

const { Payload } = await getMfflClient.send(new GetMediaForFragmentListCommand({
  StreamName: "factory-cam-01",
  Fragments: fragmentNumbers,  // from ListFragments above, max 1000 per call
}));

// Payload is a Node.js Readable or browser ReadableStream
// You MUST consume it — leaving it open holds an HTTP connection

If your time window spans more than 1,000 fragments — roughly 33 minutes at one fragment per two seconds — you must batch your fragment numbers into groups of 1,000 and make multiple GetMediaForFragmentList calls. The ListFragments stage already gave you all fragment numbers, so batching is a simple while (fragmentNumbers.length) loop over slices of 1,000.

Stage 3: Decode frames with ffmpeg

The MKV binary from KVS is a valid Matroska container. Pipe it through ffmpeg to extract individual JPEG frames:

import { spawn } from "child_process";
import { Readable } from "stream";
import { mkdirSync } from "fs";
import { join } from "path";

async function extractFrames(mkvPayload, outputDir, fps = 1) {
  mkdirSync(outputDir, { recursive: true });

  const ffmpeg = spawn("ffmpeg", [
    "-i",    "pipe:0",                     // read MKV from stdin
    "-vf",   `fps=${fps}`,                 // extract N frames per second
    "-q:v",  "2",                          // JPEG quality (2=high, 31=low)
    join(outputDir, "frame-%04d.jpg"),
    "-y",
  ], { stdio: ["pipe", "ignore", "pipe"] });

  const readable = mkvPayload instanceof Readable
    ? mkvPayload
    : Readable.fromWeb(mkvPayload);

  readable.pipe(ffmpeg.stdin);

  return new Promise((resolve, reject) => {
    ffmpeg.on("close", code => {
      if (code === 0) resolve(outputDir);
      else reject(new Error(`ffmpeg exited ${code}`));
    });
    ffmpeg.stderr.on("data", d => {
      if (d.toString().includes("Error")) console.error("[ffmpeg]", d.toString());
    });
  });
}

Setting fps=1 gives you one frame per second, which is usually more than enough for incident review. For fast-moving scenes — a conveyor belt at 30 fps — set fps=0.5 or fps=2 depending on how much resolution you need. Each additional frame is another image block passed to Claude, which increases token consumption. For a 2-minute window at 1 fps you'd have 120 frames — far more than you want to send to Claude in a single call. Sample down to 10–20 frames by selecting every Nth file from the output directory.

Stage 4: Analyze frames with Claude Vision

Claude accepts up to 20 image blocks per message. Pass the extracted JPEG files as base64-encoded image blocks:

import { readFileSync, readdirSync } from "fs";
import Anthropic from "@anthropic-ai/sdk";

async function analyzeWithClaude(framesDir, question, maxFrames = 10) {
  const client = new Anthropic();

  const frameFiles = readdirSync(framesDir)
    .filter(f => f.endsWith(".jpg"))
    .sort();

  // Sample evenly across the available frames
  const step = Math.max(1, Math.floor(frameFiles.length / maxFrames));
  const selected = frameFiles.filter((_, i) => i % step === 0).slice(0, maxFrames);

  const imageBlocks = selected.map(filename => ({
    type: "image",
    source: {
      type: "base64",
      media_type: "image/jpeg",
      data: readFileSync(join(framesDir, filename)).toString("base64"),
    },
  }));

  const { content } = await client.messages.create({
    model: "claude-opus-4-7",
    max_tokens: 1024,
    messages: [{
      role: "user",
      content: [
        ...imageBlocks,
        { type: "text", text: question },
      ],
    }],
  });

  return content[0].text;
}

const analysis = await analyzeWithClaude(
  "/tmp/kvs-frames",
  "These frames are from a factory assembly line. Describe what you see. Is there anything that looks like an equipment failure, misalignment, or safety hazard?"
);

For the full archived media API reference — HLS streaming session URLs for human playback, DASH URLs for enterprise players, and the live GetMedia streaming path — see the KVS archived media deep-dive.

Fragment arrival lag: the gotcha that breaks near-real-time queries

After a producer writes frames to KVS, there is a 2–5 second delay before those fragments appear in ListFragments responses. This matters when your MCP tool's time window extends to "just now."

If you query EndTimestamp: new Date() in ON_DEMAND mode, you will routinely miss the most recent 2–5 fragments because they haven't been indexed yet. The fix is a 10-second buffer:

const endTime = new Date(Date.now() - 10_000); // back off 10s from "now"

The LIVE playback mode in GetHLSStreamingSessionURLCommand handles this automatically — it maintains a rolling window that always trails the live edge by one fragment duration. ON_DEMAND mode does not, because it treats the timestamp range as a hard boundary. For MCP tools that need "the last N minutes of footage," use LIVE_REPLAY mode in HLS if you're returning a playback URL to a human reviewer, and manually subtract the buffer if you're using ListFragments for frame extraction.

Retention: why DataRetentionInHours=0 silently breaks archived access

This is the most common KVS misconfiguration for new teams. When you create a stream with DataRetentionInHours: 0 (or don't specify it — 0 is the default), fragments are delivered to live consumers but not stored. Any call to ListFragments, GetMediaForFragmentList, GetHLSStreamingSessionURL, or GetDASHStreamingSessionURL returns ResourceNotFoundException — the same error you get for a non-existent stream.

The fix is to set retention at stream creation time:

await kv.send(new CreateStreamCommand({
  StreamName: "factory-cam-01",
  DataRetentionInHours: 168,  // 7 days — set at least 1 hour for archived access
  MediaType: "video/h264",
}));

For compliance archival use cases, KVS supports up to 87,600 hours (10 years). Changing retention on an existing stream is non-destructive — use UpdateDataRetentionCommand with Operation: "INCREASE_DATA_RETENTION" and the CurrentVersion field (from DescribeStreamCommand) for optimistic concurrency control. You cannot change retention from 0 to non-zero retroactively for data already ingested — older fragments without a retention window were never stored.

WebRTC signaling: when you need sub-second latency

The archived media pipeline has an inherent lag: fragments arrive 2–5 seconds after ingestion, and GetMediaForFragmentList adds another round-trip. For use cases where the agent needs to perceive the current state of a live camera — a robot teleoperation agent, a real-time quality inspection loop, a live security review — WebRTC signaling channels provide sub-second latency without the archived media roundtrip.

KVS WebRTC uses a single-master / multi-viewer topology: one MASTER (the camera or IoT device) streams video to up to 10 concurrent VIEWERs. MCP servers act as VIEWERs. The signaling channel is a named rendezvous resource; the actual video flows peer-to-peer.

The critical gotcha in the WebRTC setup is the ICE server config client endpoint. You need two endpoints from the channel: a WSS endpoint for the signaling WebSocket, and an HTTPS endpoint for GetIceServerConfigCommand. Many developers mistakenly pass the WSS endpoint to both — the ICE config request must use the HTTPS endpoint:

import { KinesisVideoClient, GetSignalingChannelEndpointCommand } from "@aws-sdk/client-kinesis-video";
import { KinesisVideoSignalingClient, GetIceServerConfigCommand } from "@aws-sdk/client-kinesis-video-signaling";

const { ResourceEndpointList } = await kv.send(new GetSignalingChannelEndpointCommand({
  ChannelARN: channelArn,
  SingleMasterChannelEndpointConfiguration: {
    Protocols: ["WSS", "HTTPS"],
    Role: "VIEWER",
  },
}));

const signalingEndpoint = ResourceEndpointList.find(e => e.Protocol === "WSS")?.ResourceEndpoint;
const httpsEndpoint     = ResourceEndpointList.find(e => e.Protocol === "HTTPS")?.ResourceEndpoint;

// Critical: KinesisVideoSignalingClient must use the HTTPS endpoint, NOT the WSS endpoint
const kvSignaling = new KinesisVideoSignalingClient({
  region: "us-east-1",
  endpoint: httpsEndpoint,
});

const { IceServerList } = await kvSignaling.send(new GetIceServerConfigCommand({
  ChannelARN: channelArn,
  ClientId: "agent-" + crypto.randomUUID(),
}));

const iceServers = IceServerList.map(s => ({
  urls: s.Uris,
  username: s.Username,
  credential: s.Password,
}));

TURN credentials from GetIceServerConfig expire after the TTL in the response (default 300 seconds). For long-running VIEWER sessions, refresh credentials before expiry and update the peer connection's ICE server configuration. See the KVS WebRTC signaling guide for the full VIEWER peer connection lifecycle including SDP offer/answer exchange and ICE candidate forwarding.

One important Node.js constraint: RTCPeerConnection is not available natively in Node.js. You need a native WebRTC binding — wrtc (node-webrtc) or @roamhq/wrtc — to use the amazon-kinesis-video-streams-webrtc-sdk-js package in a server-side MCP tool. Browser-based MCP frontends can use the browser's native WebRTC without any additional packages.

Rekognition Stream Processors: event-driven video AI without a frame loop

The archived media pipeline and WebRTC both require your MCP server to actively retrieve video — either by querying a time window or by maintaining a peer connection. For many monitoring use cases, you don't want your agent polling; you want it to respond when something specific happens.

Rekognition Stream Processors solve this by running a continuous analysis loop on a live KVS stream and emitting structured events to a Kinesis Data Stream whenever detections match your criteria. The processor is managed by Rekognition's infrastructure — you just configure it, start it, and consume the KDS stream:

ModeWhat it detectsOutputUse case
ConnectedHomePERSON, PET, PACKAGE (and ALL for future labels)KDS + S3 snapshotSmart entrance, delivery detection, occupancy monitoring
FaceSearchSpecific faces from a Rekognition Face CollectionKDS onlyEmployee access control, known person alerts

A common pattern for MCP servers: when the KDS consumer receives a PACKAGE detection event, it uses the FragmentNumber field in the event payload to call GetMediaForFragmentList for exactly that fragment, extract the frame, and feed it to Claude Vision for a richer description than Rekognition's bounding box provides. This combines the efficiency of event-driven triggering with the semantic richness of a large vision model:

function handleConnectedHomeEvent(event) {
  const labels = event.ConnectedHomeDetection?.Labels ?? [];
  for (const label of labels) {
    if (label.Name === "PACKAGE" && label.Confidence > 80) {
      const fragmentNumber = event.InputInformation.KinesisVideo.FragmentNumber;
      // Use the fragment number directly — no ListFragments needed
      extractAndAnalyze(fragmentNumber, "factory-cam-01");
    }
  }
}

async function extractAndAnalyze(fragmentNumber, streamName) {
  const { Payload } = await getMfflClient.send(new GetMediaForFragmentListCommand({
    StreamName: streamName,
    Fragments: [fragmentNumber],  // exact fragment from the detection event
  }));
  const framesDir = await extractFrames(Payload, `/tmp/kvs-${fragmentNumber}`);
  const analysis = await analyzeWithClaude(framesDir, "Describe this package delivery.");
  console.log("Package analysis:", analysis);
}

Key operational gotcha: ConnectedHome stream processors require both KDS and S3 output. If you omit Output.S3Destination when creating a ConnectedHome processor, the creation call fails with a validation error. FaceSearch does not have this requirement — it only needs a KDS destination. For complete details on processor creation, IAM role setup, startup polling, and the event schema, see the KVS Rekognition Stream Processor guide.

IAM structure for a production MCP video tool

A production MCP server that handles video should use two IAM roles, not one:

Keeping write-only IoT device credentials (which have kinesisvideo:PutMedia) completely separate from the MCP server's read-only runtime role limits the blast radius if either credential is compromised. IAM setup tips for multi-service AWS integrations are covered in the AWS IAM guide for MCP servers.

Key gotchas consolidated

Across the four KVS subsystems — stream management, archived media, WebRTC, and Rekognition integration — these are the mistakes that show up most often in MCP server integrations:

  1. DataRetentionInHours: 0 (the default) means no archived access. Every ListFragments and GetMediaForFragmentList call will return ResourceNotFoundException. Set retention at stream creation time — you cannot retroactively archive fragments that were never stored.
  2. GetDataEndpointCommand is mandatory for every media operation. Using the standard KVS regional endpoint for media API calls fails with ResourceNotFoundException. Cache the endpoint per (stream, API name) — it's stable unless the stream is recreated.
  3. ICE server config uses the HTTPS signaling endpoint, not WSS. Passing the WSS endpoint to KinesisVideoSignalingClient causes connection errors that look like credential failures.
  4. Fragment arrival lag for ON_DEMAND mode is 2–5 seconds. Back off your EndTimestamp by 10 seconds when querying a time window that includes "just now."
  5. ConnectedHome stream processors require both KDS and S3 output. Omitting S3Destination causes creation to fail. FaceSearch does not have this requirement.
  6. Stream processor startup is async and takes 30–90 seconds. StartStreamProcessorCommand returns immediately; poll DescribeStreamProcessorCommand until Status === "RUNNING" before treating the processor as active.
  7. WebRTC requires a native Node.js binding. RTCPeerConnection doesn't exist in Node.js. Install wrtc or @roamhq/wrtc for server-side WebRTC in your MCP tool.
  8. Producer timestamps from IoT devices can drift. Always use SERVER_TIMESTAMP as the FragmentSelectorType for time-range queries unless you're certain your device clocks are synchronized.

Choosing the right retrieval path

Three retrieval patterns exist in KVS. The right one depends on latency tolerance and whether the query is reactive or proactive:

PatternLatencySetup complexityBest for
Archived media (ListFragments + GetMediaForFragmentList)Seconds to minutesLow — two API callsRetrospective incident review, scheduled analysis, audit
Live GetMedia stream2–5 seconds behind liveLow — one API callNear-real-time frame sampling without full WebRTC setup
WebRTC signaling channelUnder 1 secondHigh — signaling channel + ICE + native bindingReal-time agent perception, robot teleoperation, live inspection
Rekognition Stream Processor + KDSSeconds (event-driven)Medium — processor + KDS consumerTriggered analysis when specific labels/faces appear

For most MCP server integrations, the archived media pipeline is the starting point: it's the simplest to implement, requires no persistent connection, and covers the majority of "agent reviews what the camera saw" use cases. Add WebRTC when sub-second latency is a hard requirement, and add Rekognition Stream Processors when you need event-driven triggering rather than query-on-demand.

Detailed guides in this series

Related AWS AI and streaming guides: Rekognition label detection for MCP servers · Kinesis Data Streams for MCP servers · Amazon Bedrock for MCP servers · AWS IoT Core for MCP servers