# rtcStats — LLMs Full Reference This file concatenates the full llms.txt content for rtcstats.com, rtcstats-js, and rtcstats-server. For the index-only version see: https://rtcstats.com/llms.txt --- # rtcStats > AI-powered WebRTC session analysis. Upload a WebRTC dump (webrtc-internals or rtcstats file) or connect via API/MCP. rtcStats reads the dump and returns high level metrics, Observations, an Experience Score, and a plain-English AI summary of what went wrong on the call. rtcStats is a SaaS for developers troubleshooting and monitoring WebRTC applications. The collection layer (rtcstats-js + rtcstats-server) is open source and self-hosted. The analysis layer runs on rtcstats.com. No vendor lock-in: customers choose what to send. The pitch: "AI reads the dump so you don't have to." ## The problem rtcStats solves You're debugging a WebRTC call at 11pm. A user reported "video froze around 2:14." You have a webrtc-internals dump or an rtcstats file. Now you need to find the root cause. Without rtcStats: open the dump in another tab, scroll through thousands of getStats() entries, mentally pattern-match from raw metrics to root cause, write it up in a Slack thread. This takes 30-60 minutes for an experienced engineer, longer for anyone else. With rtcStats: upload the dump (or have rtcstats-js send it automatically). Get back Observations (what happened), an Experience Score (how bad it was), and an AI Summary (plain-English explanation). Time to root cause drops to minutes. For AI agents: rtcStats is the analysis layer that an AI coding assistant or debugging agent queries when it encounters a WebRTC quality issue. Instead of the agent attempting to parse raw getStats() JSON (which overflows its context window and loses temporal correlation), the agent queries rtcStats and receives structured, actionable analysis it can reason about. ## Docs - [API reference](https://rtcstats.com/api-docs): REST endpoints, auth, error codes, credit consumption rules - [API reference (Markdown)](https://rtcstats.com/api-docs.md): server-rendered Markdown version of the API reference for non-browser clients (no JavaScript required) - [OpenAPI spec](https://rtcstats.com/api/openapi): machine-readable OpenAPI 3.0 JSON (same content as the API reference, parseable by AI agents) - [MCP server](https://rtcstats.com/integrations/mcp): Model Context Protocol (Anthropic's agent standard, not a media control plane) server for WebRTC stats. Streamable HTTP endpoint, tools (get_quota, list_sessions, get_session, get_observation_explanation), prompts and an observation resource, Bearer auth. Developer plan. - [rtcstats-js](https://github.com/rtcstats/rtcstats): client SDK for WebRTC apps - [rtcstats-server](https://github.com/rtcstats/rtcstats): self-hosted collector server ## Quickstart 1. Create an application token in the dashboard under Settings > Applications (Developer plan or above) and send it as `Authorization: Bearer ` on every call. 2. `GET https://api.rtcstats.com/v1.0/quota` to verify the token and read the remaining credits. 3. `POST https://api.rtcstats.com/v1.0/analyze` with the raw dump as the body (`Content-Type: application/octet-stream`, one credit); add `?save=true` to store the session. 4. `GET https://api.rtcstats.com/v1.0/sessions` to list stored sessions, then `GET /v1.0/sessions/{rtcstatsId}` for the full analysis of one. 5. Connect an MCP client to `https://api.rtcstats.com/v1.0/mcp` with the same Bearer token (tools: get_quota, list_sessions, get_session, get_observation_explanation, plus prompts and an observation resource). Full contract: OpenAPI 3.0 JSON at https://rtcstats.com/api/openapi (Markdown rendering at https://rtcstats.com/api-docs.md). ## Guides - [How to debug a webrtc-internals dump with AI](https://rtcstats.com/blog/debug-webrtc-internals-dump-with-ai): upload a webrtc-internals dump and rtcStats returns Observations, an Experience Score, and a plain-English summary of what went wrong on the call, in under 30 seconds. Also covers why pasting a raw dump into a general chatbot fails, and querying analyzed sessions from Claude Code or Cursor over the MCP server (Developer plan). ## Analysis Output Schema The session payload returned by the MCP `get_session` tool, by `GET /v1.0/sessions/{rtcstatsId}` and by `POST /v1.0/analyze` (identical `data` object; the version that produced it is the envelope `processorVersion`): ```json { "rtcstatsId": "uuid (always present)", "rtcstatsUrl": "string (always present) — dashboard URL to open the rtcstats session", "embedUrl": "string (omitted on non-Enterprise; only present on Enterprise plan, where it is always computed — but access to the embedded viewer additionally requires the embedding feature to be active)", "processorVersion": "string (e.g. '1.9.0'), the @rtcstats/rtcstats-processor version resolved at response time", "data": { "uploadTimestamp": "ISO8601, when the dump was analyzed/processed", "title": "string", "callStart": "ISO8601", "callEnd": "ISO8601", "durationMs": "number", "experienceScore": "float 0.0-100.0 or null", "audioScore": "float or null", "videoScore": "float or null", "connectivityScore": "float or null", "connectivity": "string (e.g. 'DIRECT/UDP'; local candidate only, a remote relay alone is DIRECT)", "connectionIPType": "string ('IPv4' | 'IPv6'), omitted when unresolved", "observationsCount": { "high": "number", "medium": "number", "low": "number", "info": "number" }, "observations": [ { "type": "string (observation type key, e.g. 'turnNoConfig', 'slowDtlsEstablishment'; open set, ignore a type you do not know)", "severity": "info | low | medium | high", "category": "string (e.g. 'connections', 'streams', 'pairs')", "tags": ["string (e.g. 'network', 'connectivity', 'audio')"], "source": { "pid": "string (peer connection id; connections, pairs, streams, datachannels, logs)", "sid": "string (stream/datachannel report id; streams, datachannels)", "cpid": "string (candidate-pair id; pairs)", "did": "string (device entry id; devices)", "rid": "string (device row index; devices)", "timestamp": "string (device entry time, ISO-like; devices)", "ssrcId": "number (stream SSRC, W3C unsigned long; streams)", "labelId": "string (device name; devices)" }, "label": "string (DEPRECATED, removed in the next schema version; overloaded legacy id: numeric SSRC for streams, report id for datachannels, device name for devices; read source.ssrcId / source.sid / source.labelId instead)", "firstSeenAt": "integer epoch ms, omitted when no source timestamp is known; equals periods[0].startTimestamp when periods is set", "periods": "optional array of { startTimestamp, endTimestamp } (integer epoch ms): the precise intervals where the condition held, at most 20", "durationInPercent": "number (optional, for stream-level observations)" } ], "features": { "devices": "object (device feature flags, e.g. FEATURE_MICROPHONE_USB; FEATURE_SCREEN_RESOLUTION is a string)", "globals": "object (session-wide network/media flags, e.g. use_vpn, udp_blocked; audioIn/videoIn/audioOut/videoOut and network_interfaces are counts)", "audio": "object (firstTimestampFor* epoch ms for first sound/audible sound/audible voice, in and out; null when never observed)", "client": "object (client-level rtcstats-features; only computed keys are present, absent means not known; present only when the session has a stored features file)" }, "aiSummary": { "model": "string (e.g. 'anthropic/claude-haiku-5.5')", "summary": { "highlight": "markdown string (one-line overall summary)", "network": "markdown string (connectivity analysis)", "networkScore": "string ('excellent' | 'good' | 'acceptable' | 'poor' | 'bad')", "media": "markdown string (audio/video quality analysis)", "mediaScore": "string (same values as networkScore)", "user": "markdown string (device and peripheral analysis)", "userScore": "string (same values as networkScore)" }, "version": "string (AI prompt configuration version)" }, "userAgentData": { "platform": "string", "mobile": "boolean", "brands": [{ "brand": "string", "version": "string" }], "deviceMemory": "number or null", "hardwareConcurrency": "number or null", "cpuPerformance": "number, absent when not reported (navigator.cpuPerformance tier: 0 unknown, 1 lowest)" }, "pConnectionsNumber": "number", "pConnections": "object keyed by connection id: detailed per-connection WebRTC stats, plus the rtcstats-features catalogue facts for that peer connection (absent means not known); hasStatistics false = dump holds no getStats sample for it, entry built from logs only", "streams": "object keyed by stream key ${pid}-${sid}: per-stream metrics, plus the rtcstats-features catalogue facts for that track (absent means not known)", "transports": "object keyed by connection id then transport id: ICE transports with their candidate pairs and their DTLS/SRTP parameters", "tagClouds": "array of observation tags with their totals and per-severity breakdown", "metadata": "object: clientProtocol and custom, plus conference/session/user when the rtcstats token carried them", "from": "object (continent, country, city): coarse client location, absent for dumps carrying no location data", "aggregatedStats": "object — session-wide aggregated metrics with self-describing keys ___: metric = jitter|rtt|bitrate|packetLoss|mos; scope = in_audio|out_audio|in_video|out_video; agg = avg|min|max|p5|p95|stddev; unit = ms (jitter, rtt), kbps (bitrate), percent (packetLoss), score (mos, 1-4.5). Example: rtt_out_audio_avg_ms. Session-level weighted averages: jitter_avg_ms, rtt_avg_ms. Stream counts: in_audio_count, out_audio_count, in_video_count, out_video_count. Since schema 6.9 the former unitless keys (e.g. rtt_out_audio, in_audio) are no longer present", "... additional raw WebRTC stats fields": "present in the full payload" } } ``` `rtcstatsId` and `rtcstatsUrl` are always present in the response. `embedUrl` is the embeddable viewer URL: it is only present on Enterprise plans (omitted from the response otherwise). On Enterprise it is always computed and returned, but access to the embedded view is authorized only when the embedding feature is active for the account. `aiSummary` is `null` until background generation completes, and always `null` on `POST /analyze` and on plans without the AI feature. Only the fields documented above are rendered by rtcStats and stable; other fields may appear in the object and are subject to change without notice. Use them with care. In `aiSummary.summary` text fields, a `<` is escaped as `<`; markdown renderers display `<`. Number formatting: timestamps are integers at millisecond scale; every other number keeps at most 2 decimals, except `audioLevel` values and session features (`features.client`, catalogue keys in `pConnections` and `streams`), which keep more precision. `POST /v1.0/analyze` does not store the session by default: pass `?save=true` to persist it (the response then includes `rtcstatsId` and `rtcstatsUrl`). `POST /v1.0/analyze` also speaks the same chunked protocol as `POST /v1.0/upload`, for any dump too large for one request body: send `multipart/form-data` chunks (`chunk`, `fileId`, `chunkIndex`; each returns `{"success": true}`, consumes no credit, 3MB max per chunk and 1MB recommended), then a JSON assemble request `{"assemble": true, "fileId": "...", "fileName": "optional"}` (at most 1KB). The assembled dump runs through the normal analyze pipeline (one credit). With `?save=true` on the assemble request, `fileName` names the stored session and is mirrored in the response `data.fileName` / `data.title` when provided. Assemble detection is shape-based (small JSON body matching that exact shape), so raw JSON dump bodies keep working unchanged. File size limit, per account plan: only the bytes you send are measured, so a gzipped dump counts as its compressed size, never its decompressed size; on a chunked upload the `413` `file_too_large` lands on the chunk that crosses the limit, not at assemble, and the chunks already stored are then dropped. A gzipped dump that expands past 30x the limit or 256 MiB, whichever is lower, returns `413` `file_too_large`; a chunk refused because the account's staged chunks reach 2x its limit (no cap when unlimited) returns `429` `rate_limited` with `Retry-After`, retry it; a Storage outage that outlasts the server retries returns `503` `other_issue` with `Retry-After` (5 s) on a chunk, an assemble, a stored ingest or `GET /sessions/{rtcstatsId}` (MCP `get_session`: an `isError` result), retry it; any other upload storage failure returns `500` `other_issue`. `POST /v1.0/upload` assemble body: `{"fileId": "...", "assemble": true, "fileName": "...", "tags": ["optional"]}`; the session title is `fileName` minus its last extension. Tag rule: `^[A-Za-z0-9_.:+-]{1,32}$`, case-sensitive, at most 16 per session; exact duplicates are dropped silently; refused entries come back in a top-level `rejectedTags: [{tag, reason: "invalid"|"too_many"}]`, omitted when none (a non-string entry is given as its JSON text). A repeated assemble on `upload` or `analyze?save=true` within 24 h with the same `fileId` returns `200` with the original body and no credit (`402` once the account has no credit left). `POST /v1.0/enrich` is for a rtcstats-server or any server that only needs the observations and scores projection: same Bearer auth and one-credit cost as `analyze`, but it returns only `{ data: { scores, observationsCount, observations, userAgentData }, processorVersion, generatedAt }` and never stores the session. `scores` are the five analyzer scores (`experienceScore`, `audioScore`, `videoScore`, `connectivityScore`, `observationsScore`; each a number or null). `observations` are flat, SQL-friendly trimmed records: only `type` and `severity` are always present, every other field (`category`, `tags`, `firstSeenAt`, `url`, `property`, `valueInCount`, `valueInPercent`, `averageInMs`, `maxInMs`, `durationInMs`, `durationInSeconds`, `durationInPercent`, `source`) is omitted when absent, never null; `source` is the same object as in the main API. `observationsCount` (high/medium/low/info) sums to `observations.length`. `processorVersion` is the `@rtcstats/rtcstats-processor` version and `generatedAt` is epoch ms. The payload is full and unconditional (not plan-gated). `enrich` uses the same chunked upload protocol as `upload` and `analyze` (multipart chunks then a JSON assemble request `{"assemble": true, "fileId": "..."}`; a raw dump body also works for small files); MOS follows the account token settings. Error codes, the complete `/v1.0/*` vocabulary: `authentication` (401), `forbidden` (403), `insufficient_scope` (403), `invalid_request` (400), `no_credits` (402), `file_too_large` (413), `parsing_issue` (415), `not_found` (404), `reprocess_failed` (422), `other_issue` (415, 500, or 503 with `Retry-After`), `rate_limited` (429), `gone` (410, removed endpoint, do not retry); every error body is `{ error, errorCode }`, branch on `errorCode`, never on `error`. Rate limits, per account over 60 s windows: 30 ingest requests per minute (`upload` assemble, `analyze` and `enrich` raw or assemble), 120 read requests (`sessions` list/get/delete, `quota`, `observations/{type}`, MCP tool calls and resource reads) and 600 multipart chunks; over the limit REST returns `429` with `errorCode` `rate_limited`, `Retry-After` (seconds) and `X-RateLimit-Limit` / `X-RateLimit-Remaining` / `X-RateLimit-Reset` (the three headers are on every response emitted after the check, including the `403` `insufficient_scope`; only the `401` and the plan `403` `forbidden` carry none, being refused before the check, and all three are absent when the limiter fails open), MCP tool calls return an `isError` result and `resources/read` a JSON-RPC error; `initialize`, `tools/list`, `prompts/*` and the resource listings are never limited. ## Understanding the analysis rtcStats processes a WebRTC session dump through a multi-stage pipeline. Here's what each layer means: **Calculations** are what rtcStats does immediately on the session data. Most of the session information in a webrtc-internals or an rtcstats file is time series data of metric values. Important metrics get calculated and aggregated (rates, averages, quality estimates like MOS), providing better values that offer meaningful information. For rtcStats, these are considered part of the raw stats fields themselves. **Features** are structured per-session facts (client, connection, track) distilled from the metrics and written to SQL by the open-source rtcstats-server, enabling cross-session analysis of every call. **Observations** are specific events detected in the session data. Each observation has a severity (info, low, medium or high), a category (connections, streams, pairs), and tags. Examples: "No TURN server configured" (`turnNoConfig`), "Slow DTLS establishment" (`slowDtlsEstablishment`), "High packet loss on audio track for 15% of the call" (`highPacketLoss`). Observations are facts, not interpretations. **Experience Score** (0-100) is a composite quality rating for the entire session, broken into sub-scores: audio, video, and connectivity. The score answers "how bad was this call?" in a single number. Use it for monitoring trends across sessions, setting quality alerts, and benchmarking. **AI Summary** is a plain-English explanation of the call, organized into network, media, and user device sections. Each section includes a qualitative score (excellent, good, acceptable, poor or bad). The summary is written for an engineer who needs to understand the problem without reading the raw observations. Requires Developer plan or above. ## MCP Connect an MCP client to `https://api.rtcstats.com/v1.0/mcp` (POST, stateless JSON-RPC). Include `Authorization: Bearer ` on every request, `initialize` included: a missing or invalid token is HTTP `401` with `WWW-Authenticate`, a plan without API access `403` `forbidden`. Requires Developer plan or above. Get a token at Settings > Applications. Tools: - `get_quota`: returns `{accountName, accountPlan, allowedCredits, remainingCredits, maxFileSizeBytes, maxChunkSizeBytes}`. `maxFileSizeBytes` is the uploaded bytes allowed per dump (`null` when unlimited) and `maxChunkSizeBytes` the per-chunk cap: read them before uploading rather than discovering the limit through a `413`. `accountPlan` is the effective plan (`developer`, `trial_developer`, `enterprise`). `remainingCredits` is the combined monthly + purchased top-up pool. - `list_sessions`: returns `{total, totalCount, page, limit, totalPages, hasMore, data: [{rtcstatsId, createdAt, sessionStart, sessionEnd, title, rtcstatsUrl, embedUrl, abstract}]}`. `rtcstatsId` and `rtcstatsUrl` are always present. `sessionStart` and `sessionEnd` can be null. `embedUrl` is omitted on non-Enterprise plans. `abstract` is the denormalized session summary used to drive the filters (browser/browserVersion/os/osVersion, userId/conferenceId/sessionId, experienceScore, scoreBand `"low"|"medium"|"high"|"unrated"`, connectivity, observationTypes/observationTags, observationsHigh/Medium counts, observationMinorFlags with observationsLow/Info counts). `observationTypes` matches the `observationTypes` filter; `observationMinorFlags` lists the low/info types, which no filter reads. Every key is always present when `abstract` is non-null; `abstract` itself is `null` for rows not yet indexed. Optional filters: `name` (array, case-insensitive substring on the session title, ANY of, up to 20), `observationTypes` (array, exact observation type names, ANY of, up to 20; only high/medium observations are indexed; open set, read the values from `abstract.observationTypes` and from `data.observations[].type`), `observationTags` (array, ANY of: connectivity/security/audio/video/datachannel/outbound/inbound/peripheral/behavior/network/configuration/cpu/bug; tags of high/medium observations only), `os`, `browser`, `browserVersion` (major version only, e.g. "142"), `userId`, `conferenceId`, `sessionId` (exact match), `hasHigh`/`hasMedium` (boolean, sessions with that observation severity), `hasLowScore` (experience score < 60) / `hasMediumScore` (60-79) / `hasHighScore` (>= 80). Different filters are AND-combined; multiple values within one filter are OR-combined. Score bands match the dashboard score colors. The REST endpoint `GET /v1.0/sessions` accepts the same filters as query params (array filters repeated or comma-separated; booleans as `?hasHigh=true`). Pagination: `limit` (1-1000, default 100) and `page` (default 1), newest first; `total` counts `data`, `totalCount` counts all matches; fetch the next page while `hasMore`; out-of-range values are `400` `invalid_request` (tool error on MCP). - `get_session`: input `{rtcstatsId: UUID}`, returns `{rtcstatsId, rtcstatsUrl, processorVersion, embedUrl, data}`. `rtcstatsId`, `rtcstatsUrl` and `processorVersion` are always present. `embedUrl` is the embeddable viewer URL, only present on Enterprise plans (omitted otherwise). `data` is the session payload shown under Analysis Output Schema above, identical to what `GET /v1.0/sessions/{rtcstatsId}` returns. - `get_observation_explanation`: input `{type}` (exact, case-sensitive), returns the same object as `GET /v1.0/observations/{type}`; an unknown type is a tool error. Resource `rtcstats://observations/{type}` (`text/markdown`): the `get_observation_explanation` object rendered as Markdown; an unknown type is JSON-RPC error `-32602` with `data.uri`; no list (`resources/list` is empty), read the types a session carries; Bearer-gated, read bucket. Errors: an unknown tool is JSON-RPC `-32602`; error messages carry no `MCP error` prefix. Prompts: `what_changed_since` (`since`, `YYYY-MM-DD`), `sessions_worth_opening` (`days` default 7, `count` default 5), `explain_session_observations` (`rtcstatsId`, UUID); each returns one user message that drives the tools above; never rate limited; always send `arguments` (`{}` when empty), an omitted key is `-32602`. MCP tools, prompts and the resource are read-only and do not consume analyze credits. `GET /v1.0/observations` was removed on 2026-09-18 and answers `410` `gone` with a `Sunset` header, with or without a token: there is no published list of observation types, read them from `data.observations[].type` and `abstract.observationTypes`. `GET /v1.0/observations/{type}` returns the explanation of one type, `{type, title, description, severities, tags, updatedAt, sections: [{heading, markdown}], related: [{type, title}]}` (Markdown, absolute links), read bucket, no credit; `404` `not_found` for an unknown or wrong-case type. **Token setup:** Settings is in the left-hand sidebar. Go to the Applications tab and create a new application. The token is shown once at creation and cannot be read back — copy it immediately. Store it as your `Authorization: Bearer` value. If lost, create a new application. **Token scope:** a token is created `full` or `read_only`; a read-only one passes every read and is refused with `403` `insufficient_scope` on `POST /v1.0/upload`, `POST /v1.0/analyze`, `POST /v1.0/enrich` and `DELETE /v1.0/sessions/{rtcstatsId}`. ## Pricing One credit = one file analyzed. Monthly credits do not roll over; purchased credits do. | Plan | Price | Credits/mo | Team | Retention | Full analysis | |------------|-----------|------------|------|-----------|----------------| | Free | $0 | 10 | 3 | 1 month | Month 1 only | | Developer | $239/mo | 500 | 10 | 3 months | Yes | | Enterprise | $1,199/mo | 5,000 | 50 | 3 months | Yes + embeds | Annual pricing: Developer $199/mo, Enterprise $999/mo. Top-up credits (carry over): $100/5K, $500/50K, $2,500/500K. API access requires Developer plan or above. MCP requires Developer plan or above. ## OSS + SaaS Architecture Open source (self-hosted by the customer): - rtcstats-js: `npm install @rtcstats/rtcstats-js` — client SDK for WebRTC apps - rtcstats-server: github.com/rtcstats/rtcstats — collector server SaaS (rtcstats.com): - Receives sessions from rtcstats-server, manual file upload, or direct API - Runs analysis pipeline: Observations → Experience Score → AI Summary - Customer controls sampling: what gets sent, when, for which users --- # rtcstats-js > Client-side WebRTC monitoring SDK. Intercepts RTCPeerConnection API calls and sends periodic getStats() data to a self-hosted rtcstats-server collector. ## Install ```bash npm install @rtcstats/rtcstats-js ``` ## Typical usage ```js import { wrapRTCStatsWithDefaultOptions } from '@rtcstats/rtcstats-js'; const trace = wrapRTCStatsWithDefaultOptions(); trace.connect('wss://your-rtcstats-server.example.com' + window.location.pathname); // RTCPeerConnection is now intercepted automatically — no changes to your existing code const pc = new RTCPeerConnection(config); ``` `wrapRTCStatsWithDefaultOptions()` wraps `RTCPeerConnection` on the `window` object. All peer connections created after this call are automatically instrumented. ## Configuration options ```js import { WebSocketTrace, wrapRTCPeerConnection } from '@rtcstats/rtcstats-js'; const trace = new WebSocketTrace({ countReloads: true, // track page reloads via sessionStorage log: console.warn.bind(console) // callback for SDK log output }); wrapRTCPeerConnection(trace); trace.connect('wss://your-rtcstats-server.example.com/session-id'); ``` ## Session identity Session identity is encoded in the WebSocket URL path or query param: ```js // Via path: trace.connect('wss://your-server.example.com/' + mySessionId); // Via token query param: trace.connect('wss://your-server.example.com/?rtcstats-token=' + myToken); ``` ## Multiple sessions (long-running apps) ```js trace.connect('wss://your-server.example.com/?rtcstats-token=session-1'); // ... call ends ... trace.close(); trace.connect('wss://your-server.example.com/?rtcstats-token=session-2'); ``` ## Custom events Report application-specific events (must begin with colon): ```js trace(':callStarted', pc, { userId: 'user-123', region: 'eu-west-1' }); trace(':callEnded', pc, { reason: 'user-hangup', duration: 142 }); ``` ## What rtcstats-js does NOT do - Does not proxy media or add latency to the call path - Does not send data to rtcstats.com directly (goes to your self-hosted rtcstats-server) - Does not capture audio/video content — only getStats() metadata and WebRTC related API calls and events ## Connection path ``` rtcstats-js (browser) → rtcstats-server (your infra) → rtcstats.com (if forwarding configured) ``` ## Links - [npm package](https://www.npmjs.com/package/@rtcstats/rtcstats-js) - [GitHub / source](https://github.com/rtcstats/rtcstats) - [rtcstats-js client SDK](https://github.com/rtcstats/rtcstats) - [rtcstats-server](https://github.com/rtcstats/rtcstats) - [rtcstats.com](https://rtcstats.com) --- # rtcstats-server > Self-hosted collector that receives WebRTC session data from rtcstats-js and optionally forwards selected sessions to rtcstats.com for analysis. > > It takes care of collection, geolocation, anonymization, feature extraction locally for every session it handles. rtcstats-server can scale horizontally and is load-balancer friendly. ## What it does - Receives dump data from rtcstats-js instances over WebSocket - Geolocates based on IP addresses in the dump data (granularity is configurable) - Anonymizes the dump by scrubbing IP addresses - Stores sessions locally - Extracts relevant features from the session, storing them in a local SQL database for analytics/BI purposes - Applies sampling rules to decide which sessions to forward to rtcstats.com for analysis - Supports multiple forwarding strategies: random, per-user, per-region, threshold-triggered, manual ## Running it **Docker (recommended):** ```bash docker run -p 3000:3000 rtcstats/rtcstats-server ``` Configuration is managed via a config file or environment variables. See the [configuration reference](https://github.com/rtcstats/rtcstats#configuration) in the repository README. **From source:** ```bash git clone https://github.com/rtcstats/rtcstats cd rtcstats npm install npm start ``` ## Sampling rules Sessions can be selected for forwarding to rtcstats.com by: - **Random** — forward X% of all sessions - **Per-user** — always forward sessions for specific identifiers (e.g., flagged users, QA accounts) - **Per-region** — forward all sessions from a given geographic zone - **Threshold-triggered** — forward sessions where a metric exceeds a threshold (e.g., packet loss > 5%) - **Manual** — application flags a session for forwarding after the fact via the rtcstats-server API ## What it does NOT do - Does not analyze sessions (analysis runs on rtcstats.com) - Does not add latency to the WebRTC call path (sidecar, not a proxy) - Does not store data permanently beyond its local buffer ## Connection path ``` rtcstats-js (browser) → rtcstats-server → api.rtcstats.com/v1.0/upload ``` ## Links - [GitHub / source + configuration reference](https://github.com/rtcstats/rtcstats) - [rtcstats.com](https://rtcstats.com) - [API reference](https://rtcstats.com/api-docs) --- # End-to-end setup How to go from a working WebRTC app to sessions appearing in your rtcstats.com dashboard. ## What you need - A WebRTC app running in the browser (any framework) - A server or container environment where you can run rtcstats-server - An rtcstats.com account (free tier works for setup verification) ## Step 1: Install rtcstats-js in your WebRTC app ```bash npm install @rtcstats/rtcstats-js ``` Add the following to your app's entry point, before any RTCPeerConnection is created: ```js import { wrapRTCStatsWithDefaultOptions } from '@rtcstats/rtcstats-js'; const trace = wrapRTCStatsWithDefaultOptions(); trace.connect('wss://your-rtcstats-server.example.com' + window.location.pathname); ``` All peer connections created after `wrapRTCStatsWithDefaultOptions()` are automatically monitored. No changes to your existing WebRTC code required. ## Step 2: Run rtcstats-server ```bash docker run -p 3000:3000 rtcstats/rtcstats-server ``` Configure forwarding to rtcstats.com via the server's config file or environment. See the [rtcstats-server README](https://github.com/rtcstats/rtcstats) for all configuration options. ## Step 3: Configure forwarding to rtcstats.com 1. Sign in at rtcstats.com, go to Settings > Applications, create an application, copy the JWT token 2. Add the token to your rtcstats-server configuration 3. Choose a sampling strategy: random (X% of sessions), per-user (flagged accounts), threshold-triggered (e.g., packet loss > 5%), or manual ## Step 4: Verify 1. Start a WebRTC call in your app. Finish that call and close the browser tab 2. Open rtcstats.com/dashboard 3. A new session should appear within 30 seconds If no session appears: check browser console for `[rtcstats]` log lines, confirm rtcstats-server is reachable at the WebSocket URL, and verify the application token in rtcstats-server config. ## What's next Once sessions are flowing: - **Debugging workflow:** When a user reports a problem, find their session in the dashboard. Read the AI Summary first, then drill into Observations for the technical root cause. Share the session link with your team. - **Monitoring at scale:** Use sampling rules to forward a percentage or all of production sessions. Track Experience Score trends over time. Set up alerts when scores drop below a threshold. Query abut Observations to figure out which are common in your deployment and may require your attention. - **AI agent integration:** Connect Claude Code, Cursor, or any MCP client to `https://api.rtcstats.com/v1.0/mcp` with your application JWT. Your AI coding assistant can then query session data directly from your IDE, query trends, and help diagnose issues without manual data export. - **API automation:** Use the REST API to build custom dashboards, integrate with your incident management system, or run automated quality reports. See the [OpenAPI spec](https://rtcstats.com/api/openapi) for the full endpoint reference. - **Upgrade path:** Free plan includes 10 credits/month with full analysis for the first month. Developer plan ($239/mo or $199/mo annual) unlocks API access, AI summaries, and 500 credits/month. Enterprise adds embedded viewer, third-party storage, and 5,000 credits/month.