Skip to main content
Glama

get_recently_watched

Retrieve a list of recently watched movies, shows, or episodes from Plex Media Server. Filter results by media type and set a limit for the number of items returned.

Instructions

Get recently watched movies and shows

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNoNumber of items to return (default: 25)
mediaTypeNoFilter by media type (movie, show, episode, all)all

Implementation Reference

  • Core handler function implementing the get_recently_watched tool logic. Primarily uses getWatchHistory but falls back to scanning libraries for recently viewed items based on lastViewedAt.
    private async getRecentlyWatched(limit: number, mediaType: string) {
      // Use the working watch history function as the foundation
      try {
        const historyResult = await this.getWatchHistory(limit, undefined, mediaType);
        const historyData = JSON.parse(historyResult.content[0].text);
        
        // Transform watch history into recently watched format
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify({
                recentlyWatched: historyData.watchHistory || [],
                totalCount: historyData.totalSessions || 0,
                note: "Retrieved from watch history data",
              }, null, 2),
            },
          ],
        };
      } catch (error) {
        // Fallback to library metadata approach
        try {
          const librariesData = await this.makeRequest("/library/sections");
          const libraries = librariesData.MediaContainer?.Directory || [];
          
          let allRecentItems: any[] = [];
          
          for (const library of libraries) {
            try {
              const params: Record<string, any> = {
                sort: "lastViewedAt:desc",
                "X-Plex-Container-Size": Math.ceil(limit / libraries.length) + 5,
              };
              
              if (mediaType !== "all") {
                params.type = this.getPlexTypeId(mediaType);
              }
              
              const contentData = await this.makeRequest(`/library/sections/${library.key}/all`, params);
              const content = contentData.MediaContainer?.Metadata || [];
              
              // Filter items that have been viewed recently
              const viewedContent = content.filter((item: any) => 
                item.lastViewedAt && item.viewCount > 0
              );
              
              allRecentItems.push(...viewedContent);
            } catch (libError) {
              continue;
            }
          }
          
          // Sort by last viewed date and take requested number
          allRecentItems.sort((a: any, b: any) => (b.lastViewedAt || 0) - (a.lastViewedAt || 0));
          allRecentItems = allRecentItems.slice(0, limit);
          
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  recentlyWatched: allRecentItems.map((item: any) => ({
                    ratingKey: item.ratingKey,
                    title: item.title,
                    type: item.type,
                    year: item.year,
                    lastViewedAt: item.lastViewedAt,
                    viewCount: item.viewCount,
                    duration: item.duration,
                    viewOffset: item.viewOffset || 0,
                    progress: item.viewOffset && item.duration ? 
                      Math.round((item.viewOffset / item.duration) * 100) : 100,
                  })),
                  totalCount: allRecentItems.length,
                  note: "Retrieved from library metadata",
                }, null, 2),
              },
            ],
          };
        } catch (fallbackError) {
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  recentlyWatched: [],
                  totalCount: 0,
                  error: "Recently watched data not available",
                  message: "Unable to retrieve recently watched content from this Plex server",
                }, null, 2),
              },
            ],
          };
        }
      }
    }
  • Input schema definition for the get_recently_watched tool, specifying parameters limit and mediaType.
    inputSchema: {
      type: "object",
      properties: {
        limit: {
          type: "number",
          description: "Number of items to return (default: 25)",
          default: 25,
        },
        mediaType: {
          type: "string",
          description: "Filter by media type (movie, show, episode, all)",
          enum: ["movie", "show", "episode", "all"],
          default: "all",
        },
      },
    },
  • src/index.ts:110-129 (registration)
    Tool registration in the ListTools response, defining name, description, and input schema for get_recently_watched.
    {
      name: "get_recently_watched",
      description: "Get recently watched movies and shows",
      inputSchema: {
        type: "object",
        properties: {
          limit: {
            type: "number",
            description: "Number of items to return (default: 25)",
            default: 25,
          },
          mediaType: {
            type: "string",
            description: "Filter by media type (movie, show, episode, all)",
            enum: ["movie", "show", "episode", "all"],
            default: "all",
          },
        },
      },
    },
  • Dispatcher case in the CallToolRequest handler that routes to the getRecentlyWatched method.
    case "get_recently_watched":
      return await this.getRecentlyWatched(
        ((args as any)?.limit as number) || 25,
        (args as any)?.mediaType as string || "all"
      );
  • Invocation of helper method getWatchHistory used as primary data source for recently watched items.
        const historyResult = await this.getWatchHistory(limit, undefined, mediaType);
        const historyData = JSON.parse(historyResult.content[0].text);
        
        // Transform watch history into recently watched format
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify({
                recentlyWatched: historyData.watchHistory || [],
                totalCount: historyData.totalSessions || 0,
                note: "Retrieved from watch history data",
              }, null, 2),
            },
          ],
        };
      } catch (error) {
        // Fallback to library metadata approach
        try {
          const librariesData = await this.makeRequest("/library/sections");
          const libraries = librariesData.MediaContainer?.Directory || [];
          
          let allRecentItems: any[] = [];
          
          for (const library of libraries) {
            try {
              const params: Record<string, any> = {
                sort: "lastViewedAt:desc",
                "X-Plex-Container-Size": Math.ceil(limit / libraries.length) + 5,
              };
              
              if (mediaType !== "all") {
                params.type = this.getPlexTypeId(mediaType);
              }
              
              const contentData = await this.makeRequest(`/library/sections/${library.key}/all`, params);
              const content = contentData.MediaContainer?.Metadata || [];
              
              // Filter items that have been viewed recently
              const viewedContent = content.filter((item: any) => 
                item.lastViewedAt && item.viewCount > 0
              );
              
              allRecentItems.push(...viewedContent);
            } catch (libError) {
              continue;
            }
          }
          
          // Sort by last viewed date and take requested number
          allRecentItems.sort((a: any, b: any) => (b.lastViewedAt || 0) - (a.lastViewedAt || 0));
          allRecentItems = allRecentItems.slice(0, limit);
          
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  recentlyWatched: allRecentItems.map((item: any) => ({
                    ratingKey: item.ratingKey,
                    title: item.title,
                    type: item.type,
                    year: item.year,
                    lastViewedAt: item.lastViewedAt,
                    viewCount: item.viewCount,
                    duration: item.duration,
                    viewOffset: item.viewOffset || 0,
                    progress: item.viewOffset && item.duration ? 
                      Math.round((item.viewOffset / item.duration) * 100) : 100,
                  })),
                  totalCount: allRecentItems.length,
                  note: "Retrieved from library metadata",
                }, null, 2),
              },
            ],
          };
        } catch (fallbackError) {
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  recentlyWatched: [],
                  totalCount: 0,
                  error: "Recently watched data not available",
                  message: "Unable to retrieve recently watched content from this Plex server",
                }, null, 2),
              },
            ],
          };
        }
      }
    }
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. It states what the tool does but doesn't mention any behavioral traits such as whether it requires authentication, has rate limits, returns paginated results, or what the output format might be. This is a significant gap for a tool with no annotation coverage.

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 a single, efficient sentence that directly states the tool's purpose without any wasted words. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly.

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?

Given the lack of annotations and no output schema, the description is incomplete. It doesn't address behavioral aspects like authentication needs or output format, and while the schema covers parameters well, the overall context for a tool that likely interacts with user data is underspecified.

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?

The input schema has 100% description coverage, clearly documenting both parameters with defaults and enums. The description doesn't add any semantic details beyond what the schema provides, such as explaining the context of 'recently watched' or how filtering works, so it meets the baseline for high schema coverage.

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 verb 'Get' and the resource 'recently watched movies and shows', providing a specific purpose. However, it doesn't explicitly differentiate from sibling tools like 'get_watch_history' or 'get_on_deck', which might have overlapping functionality, so it doesn't reach the highest score.

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 like 'get_watch_history' or 'get_on_deck'. It lacks context about prerequisites, exclusions, or specific scenarios, leaving the agent to infer usage from the tool name alone.

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