get_watch_stats
Retrieve detailed watch statistics for your Plex Media Server, including plays, duration, users, libraries, and platforms, over a customizable time range for comprehensive viewing insights.
Instructions
Get comprehensive watch statistics (Tautulli-style analytics)
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| statType | No | Type of statistics to retrieve | plays |
| timeRange | No | Time range in days (default: 30) |
Implementation Reference
- src/index.ts:873-928 (handler)The core handler function for the 'get_watch_stats' tool. It fetches recent watch history sessions from Plex API, filters by time range, computes statistics based on the specified statType using helper calculate* functions, and returns formatted JSON stats with fallback to basic stats.private async getWatchStats(timeRange: number, statType: string) { const fromDate = Math.floor((Date.now() - (timeRange * 24 * 60 * 60 * 1000)) / 1000); try { // Get watch history for the time range const historyData = await this.makeRequest("/status/sessions/history/all", { "X-Plex-Container-Size": 1000, }); const sessions = historyData.MediaContainer?.Metadata || []; // Filter sessions by time range const filteredSessions = sessions.filter((session: any) => session.viewedAt && session.viewedAt >= fromDate ); let stats: any = {}; switch (statType) { case "plays": stats = this.calculatePlayStats(filteredSessions); break; case "duration": stats = this.calculateDurationStats(filteredSessions); break; case "users": stats = this.calculateUserStats(filteredSessions); break; case "libraries": stats = this.calculateLibraryStats(filteredSessions); break; case "platforms": stats = this.calculatePlatformStats(filteredSessions); break; default: stats = this.calculatePlayStats(filteredSessions); } return { content: [ { type: "text", text: JSON.stringify({ timeRange: `${timeRange} days`, statType, totalSessions: filteredSessions.length, stats, }, null, 2), }, ], }; } catch (error) { // Fallback to basic library stats if detailed history isn't available return await this.getBasicStats(timeRange, statType); } }
- src/index.ts:154-173 (schema)Input schema definition for the 'get_watch_stats' tool, specifying parameters timeRange (days, default 30) and statType (enum: plays, duration, users, libraries, platforms, default plays). This is part of the tools list returned by ListToolsRequestHandler.{ name: "get_watch_stats", description: "Get comprehensive watch statistics (Tautulli-style analytics)", inputSchema: { type: "object", properties: { timeRange: { type: "number", description: "Time range in days (default: 30)", default: 30, }, statType: { type: "string", description: "Type of statistics to retrieve", enum: ["plays", "duration", "users", "libraries", "platforms"], default: "plays", }, }, }, },
- src/index.ts:289-293 (registration)Tool dispatch/registration in the CallToolRequestSchema handler switch statement. Routes calls to 'get_watch_stats' to the getWatchStats method with parsed arguments.case "get_watch_stats": return await this.getWatchStats( ((args as any)?.timeRange as number) || 30, (args as any)?.statType as string || "plays" );
- src/index.ts:930-946 (helper)Helper function calculatePlayStats used by getWatchStats for 'plays' statType. Computes daily plays, plays by media type, total plays, and average daily plays from session data.private calculatePlayStats(sessions: any[]) { const playsByDay: Record<string, number> = {}; const playsByType: Record<string, number> = {}; sessions.forEach((session: any) => { const date = new Date(session.viewedAt * 1000).toISOString().split('T')[0]; playsByDay[date] = (playsByDay[date] || 0) + 1; playsByType[session.type] = (playsByType[session.type] || 0) + 1; }); return { totalPlays: sessions.length, playsByDay, playsByType, averagePlaysPerDay: sessions.length / Object.keys(playsByDay).length || 0, }; }