Skip to main content
Glama

search_reddit_posts

Search for Reddit posts in any subreddit using specific queries, filters, and sorting options to find relevant content.

Instructions

Search for posts in a specific subreddit

Args: subreddit: The name of the subreddit to search in (without r/) query: The search query limit: Number of posts to return (default: 10, max: 100) sort: Sort method - "relevance", "hot", "top", "new", "comments" (default: "relevance") time_filter: Time filter - "all", "day", "week", "month", "year" (default: "all")

Returns: Human readable string containing search results

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNo
queryYes
sortNorelevance
subredditYes
time_filterNoall

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler function for the 'search_reddit_posts' MCP tool. Decorated with @mcp.tool() for automatic registration and schema inference from signature/docstring. Performs client check, calls helper method, formats output, handles errors.
    @mcp.tool()
    async def search_reddit_posts(
        subreddit: str,
        query: str, 
        limit: int = 10,
        sort: str = "relevance",
        time_filter: str = "all"
    ) -> str:
        """
        Search for posts in a specific subreddit
    
        Args:
            subreddit: The name of the subreddit to search in (without r/)
            query: The search query
            limit: Number of posts to return (default: 10, max: 100)
            sort: Sort method - "relevance", "hot", "top", "new", "comments" (default: "relevance")
            time_filter: Time filter - "all", "day", "week", "month", "year" (default: "all")
    
        Returns:
            Human readable string containing search results
        """
        if reddit_client is None:
            return """Error: Reddit client not initialized. 
    
    To fix this:
    1. Copy env.example to .env: cp env.example .env
    2. Edit .env with your Reddit API credentials:
       - Get credentials from https://old.reddit.com/prefs/apps/
       - Create a 'script' type app
       - Fill in REDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET, and REDDIT_USER_AGENT
    3. Restart the MCP server
    
    Example .env content:
    REDDIT_CLIENT_ID=your_14_char_client_id
    REDDIT_CLIENT_SECRET=your_27_char_client_secret  
    REDDIT_USER_AGENT=reddit-mcp-tool:v0.2.0 (by /u/yourusername)"""
        
        try:
            posts = await reddit_client.search_posts(
                subreddit_name=subreddit,
                query=query,
                limit=min(limit, 100),
                sort=sort,
                time_filter=time_filter
            )
            
            if not posts:
                return f"No posts found in r/{subreddit} for query: '{query}'"
            
            result = f"Found {len(posts)} posts in r/{subreddit} for query: '{query}'\n\n"
            
            for i, post in enumerate(posts, 1):
                result += (
                    f"{i}. **{post['title']}**\n"
                    f"   Author: {post['author']}\n"
                    f"   Score: {post['score']} (upvote ratio: {post['upvote_ratio']:.0%})\n"
                    f"   Comments: {post['num_comments']}\n"
                    f"   Link: {post['permalink']}\n"
                    f"   Subreddit: r/{post['subreddit']}\n"
                )
                
                if post['selftext'] and len(post['selftext']) > 0:
                    preview = post['selftext'][:200] + "..." if len(post['selftext']) > 200 else post['selftext']
                    result += f"   Content: {preview}\n"
                
                result += "\n"
            
            return result
            
        except Exception as e:
            logger.error(f"Error searching posts in r/{subreddit}: {str(e)}")
            return f"Error searching posts in r/{subreddit}: {str(e)}"
  • Core helper method in RedditClient that executes the Reddit API search using asyncpraw.Reddit.subreddit.search(), extracts relevant post fields into structured dicts, and returns a list of post data.
    async def search_posts(
        self, 
        subreddit_name: str, 
        query: str, 
        limit: int = 10,
        sort: str = "relevance",
        time_filter: str = "all"
    ) -> List[Dict[str, Any]]:
        """Search for posts in a subreddit."""
        try:
            subreddit = await self.reddit.subreddit(subreddit_name)
            
            # Search posts
            posts = []
            search_results = subreddit.search(
                query, 
                limit=limit, 
                sort=sort, 
                time_filter=time_filter
            )
            
            async for submission in search_results:
                post_data = {
                    "id": submission.id,
                    "title": submission.title,
                    "author": str(submission.author) if submission.author else "[deleted]",
                    "score": submission.score,
                    "upvote_ratio": submission.upvote_ratio,
                    "url": submission.url,
                    "permalink": f"https://reddit.com{submission.permalink}",
                    "created_utc": submission.created_utc,
                    "num_comments": submission.num_comments,
                    "selftext": submission.selftext[:500] + "..." if len(submission.selftext) > 500 else submission.selftext,
                    "is_self": submission.is_self,
                    "domain": submission.domain,
                    "subreddit": str(submission.subreddit),
                }
                posts.append(post_data)
            
            return posts
            
        except Exception as e:
            raise Exception(f"Error searching posts in r/{subreddit_name}: {str(e)}")
  • Input schema defined by function parameters with type hints and comprehensive docstring describing args, defaults, and return type. Used by FastMCP for tool schema generation.
    async def search_reddit_posts(
        subreddit: str,
        query: str, 
        limit: int = 10,
        sort: str = "relevance",
        time_filter: str = "all"
    ) -> str:
        """
        Search for posts in a specific subreddit
    
        Args:
            subreddit: The name of the subreddit to search in (without r/)
            query: The search query
            limit: Number of posts to return (default: 10, max: 100)
            sort: Sort method - "relevance", "hot", "top", "new", "comments" (default: "relevance")
            time_filter: Time filter - "all", "day", "week", "month", "year" (default: "all")
    
        Returns:
            Human readable string containing search results
        """
  • FastMCP decorator that registers the function as an MCP tool, inferring name from function name, schema from signature/docstring.
    @mcp.tool()
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions default values and limits, which is helpful, but doesn't cover important aspects like rate limits, authentication requirements, error conditions, or pagination behavior. For a search tool with no annotation coverage, this leaves significant gaps.

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 well-structured and efficiently organized. It starts with a clear purpose statement, then provides a parameter table with essential details, and ends with return information. Every sentence earns its place with no wasted words.

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 (5 parameters, no annotations, but has output schema), the description is fairly complete. It documents all parameters thoroughly and mentions the return format. The output schema existence means it doesn't need to detail return values. The main gap is lack of behavioral context like rate limits or error handling.

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?

The description provides excellent parameter documentation with clear explanations of each parameter's purpose, default values, and constraints. With 0% schema description coverage, this fully compensates by adding meaning beyond what the bare schema provides. The only minor gap is not explicitly stating that 'subreddit' should be provided without the 'r/' prefix.

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: 'Search for posts in a specific subreddit' - a specific verb ('search') and resource ('posts in a specific subreddit'). It doesn't explicitly distinguish from sibling tools like 'search_reddit_all' (which searches all of Reddit vs. a specific subreddit), but the purpose is unambiguous.

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?

No guidance is provided on when to use this tool versus alternatives like 'search_reddit_all' (for searching across Reddit) or 'get_hot_reddit_posts' (for getting hot posts without a query). The description only states what the tool does, not when it's appropriate relative to siblings.

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

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