Skip to main content
Glama

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
NameRequiredDescriptionDefault
statTypeNoType of statistics to retrieveplays
timeRangeNoTime range in days (default: 30)

Implementation Reference

  • 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);
      }
    }
  • 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"
      );
  • 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,
      };
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. While 'Get' implies a read operation, it doesn't specify whether this requires authentication, what format the statistics are returned in, whether there are rate limits, or how comprehensive 'comprehensive' actually is. The description is too vague about the tool's behavior beyond the basic operation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise - a single sentence that gets straight to the point. The parenthetical '(Tautulli-style analytics)' efficiently adds helpful context without unnecessary elaboration. Every word earns its place in this description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a statistics retrieval tool with no annotations and no output schema, the description is insufficient. It doesn't explain what format the statistics are returned in, what 'comprehensive' means, or how this differs from related sibling tools. The agent would be left guessing about the actual behavior and output of this tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the schema already documents both parameters thoroughly. The description adds no additional parameter information beyond what's in the schema - it doesn't explain what 'comprehensive watch statistics' means in relation to the statType parameter or provide context about appropriate timeRange values. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Get') and resource ('comprehensive watch statistics'), and the parenthetical '(Tautulli-style analytics)' provides helpful context about the type of analytics. However, it doesn't explicitly differentiate from sibling tools like 'get_user_stats' or 'get_library_stats' which might provide overlapping or related statistics.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With sibling tools like 'get_user_stats', 'get_library_stats', and 'get_watch_history' available, there's no indication of what makes this tool distinct or when it should be preferred over those other options.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/niavasha/plex-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server