Skip to main content
Glama
tandat8503

Reddit MCP Server

by tandat8503

get_post_comments

Fetch and structure comments and replies for any Reddit post using its post_id. Optionally sort results by 'best,' 'top,' or 'new' for organized viewing.

Instructions

💬 Get comments for a Reddit post 🎯 What it does: Fetches comments and replies for any Reddit post 📝 Required: post_id (Reddit post ID, found in post URLs) ⚙️ Optional: sort ('best', 'top', 'new') 💡 Examples: • Get comments: {"post_id": "1n1nlse"} • Best comments: {"post_id": "1n1nlse", "sort": "best"} • New comments: {"post_id": "1n1nlse", "sort": "new"} 🔍 Output: Formatted comment tree with author, score, timestamp, and nested replies

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
post_idYesReddit post ID to get comments for
sortNoSort order (default: best)best

Implementation Reference

  • MCP tool handler for 'get_post_comments': extracts params, applies smart defaults, calls redditAPI.getPostComments, parses and validates response, formats comment tree with formatDataList and formatRedditComment, returns MCP-formatted text response.
    createToolHandler(async (params: z.infer<typeof SimplePostCommentsSchema>) => {
        const { post_id, sort } = params;
        
        // 🧠 Smart defaults for missing parameters
        const smartDefaults = getSmartDefaults(params, 'comments');
        const finalParams = { ...smartDefaults, post_id, sort: sort || smartDefaults.sort };
        
        const result = await redditAPI.getPostComments(post_id, finalParams.limit, finalParams.sort);
    
        if (!result.success) {
          return createErrorResponse("Error getting post comments", result.error);
        }
    
        const data = result.data;
        if (!data || !Array.isArray(data) || data.length === 0) {
          return createErrorResponse("No comments found for this post");
        }
    
        // The first element contains the post, the second contains comments
        const commentsData = data[1];
        if (!commentsData || !commentsData.data || !commentsData.data.children) {
          return createErrorResponse("No comments found for this post");
        }
    
        const comments = commentsData.data.children.map((child: any) => child.data);
        
        if (comments.length === 0) {
          return createSuccessResponse("No comments found for this post");
        }
    
        const summary = `💬 Found ${comments.length} comments for post ${post_id} (sorted by ${sort})`;
        
      // ✅ DRY: Sử dụng formatDataList helper
      const commentDetails = formatDataList(comments, formatRedditComment, COMMENT_PREVIEW_LIMIT, "comments");
    
      const resultText = `${summary}\n\n${commentDetails}`;
        return createSuccessResponse(resultText);
    })
  • Zod input schema defining required 'post_id' string and optional 'sort' enum (best, top, new) with defaults and descriptions.
    export const SimplePostCommentsSchema = z.object({
      post_id: z.string().describe("Reddit post ID to get comments for"),
      sort: z.enum(["best", "top", "new"]).default("best").describe("Sort order (default: best)")
    });
  • src/index.ts:603-653 (registration)
    MCP server.tool registration for 'get_post_comments' including name, detailed description, input schema reference, and wrapped handler function.
    server.tool(
      "get_post_comments",
      "💬 Get comments for a Reddit post\n" +
      "🎯 What it does: Fetches comments and replies for any Reddit post\n" +
      "📝 Required: post_id (Reddit post ID, found in post URLs)\n" +
      "⚙️ Optional: sort ('best', 'top', 'new')\n" +
      "💡 Examples:\n" +
      "   • Get comments: {\"post_id\": \"1n1nlse\"}\n" +
      "   • Best comments: {\"post_id\": \"1n1nlse\", \"sort\": \"best\"}\n" +
      "   • New comments: {\"post_id\": \"1n1nlse\", \"sort\": \"new\"}\n" +
      "🔍 Output: Formatted comment tree with author, score, timestamp, and nested replies",
      SimplePostCommentsSchema.shape,
      createToolHandler(async (params: z.infer<typeof SimplePostCommentsSchema>) => {
          const { post_id, sort } = params;
          
          // 🧠 Smart defaults for missing parameters
          const smartDefaults = getSmartDefaults(params, 'comments');
          const finalParams = { ...smartDefaults, post_id, sort: sort || smartDefaults.sort };
          
          const result = await redditAPI.getPostComments(post_id, finalParams.limit, finalParams.sort);
    
          if (!result.success) {
            return createErrorResponse("Error getting post comments", result.error);
          }
    
          const data = result.data;
          if (!data || !Array.isArray(data) || data.length === 0) {
            return createErrorResponse("No comments found for this post");
          }
    
          // The first element contains the post, the second contains comments
          const commentsData = data[1];
          if (!commentsData || !commentsData.data || !commentsData.data.children) {
            return createErrorResponse("No comments found for this post");
          }
    
          const comments = commentsData.data.children.map((child: any) => child.data);
          
          if (comments.length === 0) {
            return createSuccessResponse("No comments found for this post");
          }
    
          const summary = `💬 Found ${comments.length} comments for post ${post_id} (sorted by ${sort})`;
          
        // ✅ DRY: Sử dụng formatDataList helper
        const commentDetails = formatDataList(comments, formatRedditComment, COMMENT_PREVIEW_LIMIT, "comments");
    
        const resultText = `${summary}\n\n${commentDetails}`;
          return createSuccessResponse(resultText);
      })
    );
  • Supporting method in RedditAPIService: constructs and executes authenticated GET request to Reddit API endpoint `/comments/{postId}.json` with limit/sort params, handles OAuth token, rate limits, errors, returns structured ApiCallResult.
    async getPostComments(
      postId: string,
      limit: number = 25,
      sort: "best" | "top" | "new" | "controversial" | "old" | "qa" = "best",
    ): Promise<ApiCallResult> {
      const params: Record<string, any> = { limit, sort };
    
      return this.makeRequest<Array<{ data: { children: Array<{ data: RedditComment }> } }>>(
        `/comments/${postId}.json`,
        params,
      );
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: it fetches comments and replies (read operation), specifies the output format ('formatted comment tree with author, score, timestamp, and nested replies'), and mentions optional sorting. However, it doesn't cover potential rate limits, authentication needs, or pagination behavior, which are gaps for a Reddit API tool.

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 front-loaded with a clear purpose and uses bullet points efficiently for examples. Every sentence earns its place: the emoji sections (💬, 🎯, etc.) organize information without waste, and the output description is succinct. No redundant or verbose content is present.

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

Completeness4/5

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

Given the tool's moderate complexity (2 parameters, no output schema, no annotations), the description is mostly complete. It covers purpose, parameters with examples, and output format. However, it lacks details on error handling, rate limits, or authentication—common for API tools. With no output schema, the output description is helpful but could be more detailed (e.g., structure of the tree).

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

Parameters4/5

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

Schema description coverage is 100%, so the schema already documents both parameters well. The description adds value by explaining post_id ('found in post URLs'), providing examples of parameter usage, and clarifying sort options with examples. This goes beyond the schema's basic descriptions, though it doesn't add deep semantic nuances.

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

Purpose5/5

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

The description clearly states the verb 'fetches' and resource 'comments and replies for any Reddit post', making the purpose specific. It distinguishes from siblings like get_subreddit_posts (which gets posts, not comments) and get_user_profile (user-focused rather than post-focused). The emoji '💬 Get comments for a Reddit post' reinforces this distinction.

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

Usage Guidelines3/5

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

The description implies usage when needing comments for a Reddit post, but provides no explicit guidance on when to use this tool versus alternatives like search_reddit (which might find comments via search) or get_cross_posts (which focuses on cross-posting). There's no mention of prerequisites or exclusions, leaving usage context inferred rather than stated.

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/tandat8503/mcp-reddit'

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