Skip to main content
Glama

get_top_posts

Retrieve top-performing posts from any subreddit by specifying time period and quantity for content analysis or trend monitoring.

Instructions

Get top posts from a subreddit

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
subredditYesName of the subreddit
time_filterNoTime period to filter posts (e.g. 'day', 'week', 'month', 'year', 'all')week
limitNoNumber of posts to fetch

Implementation Reference

  • Main handler function implementing the get_top_posts tool logic: fetches top posts via RedditClient, formats them with formatPostInfo, generates summaries, and returns structured markdown content.
    export async function getTopPosts(params: {
      subreddit: string;
      time_filter?: string;
      limit?: number;
    }) {
      const { subreddit, time_filter = "week", limit = 10 } = params;
      const client = getRedditClient();
    
      if (!client) {
        throw new McpError(
          ErrorCode.InternalError,
          "Reddit client not initialized"
        );
      }
    
      try {
        console.log(`[Tool] Getting top posts from r/${subreddit}`);
        const posts = await client.getTopPosts(subreddit, time_filter, limit);
        const formattedPosts = posts.map(formatPostInfo);
    
        const postSummaries = formattedPosts
          .map(
            (post, index) => `
    ### ${index + 1}. ${post.title}
    - Author: u/${post.author}
    - Score: ${post.stats.score.toLocaleString()} (${(
              post.stats.upvoteRatio * 100
            ).toFixed(1)}% upvoted)
    - Comments: ${post.stats.comments.toLocaleString()}
    - Posted: ${post.metadata.posted}
    - Link: ${post.links.shortLink}
        `
          )
          .join("\n");
    
        return {
          content: [
            {
              type: "text",
              text: `
    # Top Posts from r/${subreddit} (${time_filter})
    
    ${postSummaries}
              `,
            },
          ],
        };
      } catch (error) {
        console.error(`[Error] Error getting top posts: ${error}`);
        throw new McpError(
          ErrorCode.InternalError,
          `Failed to fetch top posts: ${error}`
        );
      }
    }
  • Input schema definition for the get_top_posts tool, specifying required 'subreddit' parameter and optional 'time_filter' (enum) and 'limit'.
    name: "get_top_posts",
    description: "Get top posts from a subreddit",
    inputSchema: {
      type: "object",
      properties: {
        subreddit: {
          type: "string",
          description: "Name of the subreddit",
        },
        time_filter: {
          type: "string",
          description:
            "Time period to filter posts (e.g. 'day', 'week', 'month', 'year', 'all')",
          enum: ["day", "week", "month", "year", "all"],
          default: "week",
        },
        limit: {
          type: "integer",
          description: "Number of posts to fetch",
          default: 10,
        },
      },
      required: ["subreddit"],
    },
  • src/index.ts:434-441 (registration)
    Registration of the get_top_posts handler in the MCP server's CallToolRequestSchema switch statement, dispatching to tools.getTopPosts.
    case "get_top_posts":
      return await tools.getTopPosts(
        toolParams as {
          subreddit: string;
          time_filter?: string;
          limit?: number;
        }
      );
  • Supporting helper method in RedditClient class that makes the actual API call to fetch top posts from Reddit's OAuth API and parses the response into RedditPost objects.
    async getTopPosts(
      subreddit: string,
      timeFilter: string = "week",
      limit: number = 10
    ): Promise<RedditPost[]> {
      await this.authenticate();
      try {
        const endpoint = subreddit ? `/r/${subreddit}/top.json` : "/top.json";
        const response = await this.api.get(endpoint, {
          params: {
            t: timeFilter,
            limit,
          },
        });
    
        return response.data.data.children.map((child: any) => {
          const post = child.data;
          return {
            id: post.id,
            title: post.title,
            author: post.author,
            subreddit: post.subreddit,
            selftext: post.selftext,
            url: post.url,
            score: post.score,
            upvoteRatio: post.upvote_ratio,
            numComments: post.num_comments,
            createdUtc: post.created_utc,
            over18: post.over_18,
            spoiler: post.spoiler,
            edited: !!post.edited,
            isSelf: post.is_self,
            linkFlairText: post.link_flair_text,
            permalink: post.permalink,
          };
        });
      } catch (error) {
        console.error(
          `[Error] Failed to get top posts for ${subreddit || "home"}:`,
          error
        );
        throw new Error(`Failed to get top posts for ${subreddit || "home"}`);
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states 'Get top posts' but doesn't explain what 'top' means (e.g., by upvotes, hotness), whether it requires authentication, rate limits, or the return format (e.g., list of posts with fields). This leaves significant gaps in understanding how the tool behaves beyond basic input-output.

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, clear sentence that front-loads the core purpose without unnecessary words. It efficiently communicates the tool's function, making it easy to parse and understand quickly. There's no wasted space or redundant information.

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 complexity of fetching posts with parameters and no output schema, the description is insufficient. It lacks details on what 'top' entails, the structure of returned data, or any behavioral traits like pagination or error handling. With no annotations to fill gaps, this leaves the agent under-informed for proper use.

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?

Schema description coverage is 100%, so the schema fully documents parameters like 'subreddit', 'time_filter', and 'limit' with descriptions and defaults. The description adds no additional semantic context beyond implying filtering by time and quantity, which is already covered. Thus, it meets the baseline for high schema coverage without enhancing parameter understanding.

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 resource ('top posts from a subreddit'), making the purpose immediately understandable. It distinguishes from siblings like 'get_subreddit_info' or 'search_posts' by specifying 'top posts' rather than general information or search results. However, it doesn't explicitly differentiate from 'get_submission' or 'get_reddit_post', which might fetch individual posts, leaving some ambiguity.

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 many sibling tools like 'search_posts', 'get_submission', and 'get_user_posts', there's no indication of when 'top posts' is preferred, such as for trending content versus specific queries. This lack of context makes it harder for an agent to choose correctly among similar tools.

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

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/samy-clivolt/reddit-mcp-server'

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