Skip to main content
Glama
jordanburke

reddit-mcp-server

search_reddit

Search for posts on Reddit using keywords, filter by subreddit, sort by relevance or time, and specify content type to find specific discussions.

Instructions

Search for posts on Reddit

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNoMaximum number of results to return
queryYesThe search query
sortNoSort order: relevance, hot, top, new, commentsrelevance
subredditNoSearch within a specific subreddit (optional)
time_filterNoTime filter: hour, day, week, month, year, allall
typeNoType of content: link (posts), sr (subreddits), user (users)link

Implementation Reference

  • src/index.ts:439-494 (registration)
    Registration of the 'search_reddit' MCP tool using server.addTool, including name, description, Zod input schema, and inline execute handler that calls the RedditClient search method and formats results.
    server.addTool({
      name: "search_reddit",
      description: "Search Reddit for posts and content across subreddits",
      parameters: z.object({
        query: z.string().describe("Search query"),
        subreddit: z.string().optional().describe("Limit search to specific subreddit (without r/ prefix)"),
        sort: z.enum(["relevance", "hot", "top", "new", "comments"]).default("relevance").describe("Sort order"),
        time_filter: z.enum(["hour", "day", "week", "month", "year", "all"]).default("all").describe("Time filter"),
        limit: z.number().min(1).max(100).default(10).describe("Number of results"),
        type: z.enum(["link", "sr", "user"]).default("link").describe("Type of content to search"),
      }),
      execute: async (args) => {
        const client = getRedditClient()
        if (!client) {
          throw new Error("Reddit client not initialized")
        }
    
        if (!args.query || args.query.trim() === "") {
          throw new Error("Search query cannot be empty")
        }
    
        const posts = await client.searchReddit(args.query, {
          subreddit: args.subreddit,
          sort: args.sort,
          timeFilter: args.time_filter,
          limit: args.limit,
          type: args.type,
        })
    
        if (posts.length === 0) {
          const searchLocation = args.subreddit ? ` in r/${args.subreddit}` : ""
          return `No results found for "${args.query}"${searchLocation}.`
        }
    
        const searchResults = posts
          .map((post, index) => {
            const flags = [...(post.over18 ? ["**NSFW**"] : []), ...(post.spoiler ? ["**Spoiler**"] : [])]
    
            return `### ${index + 1}. ${post.title} ${flags.join(" ")}
    - Subreddit: r/${post.subreddit}
    - Author: u/${post.author}
    - Score: ${post.score.toLocaleString()} (${(post.upvoteRatio * 100).toFixed(1)}% upvoted)
    - Comments: ${post.numComments.toLocaleString()}
    - Posted: ${new Date(post.createdUtc * 1000).toLocaleString()}
    - Link: https://reddit.com${post.permalink}`
          })
          .join("\n\n")
    
        const searchLocation = args.subreddit ? ` in r/${args.subreddit}` : ""
        return `# Reddit Search Results for: "${args.query}"${searchLocation}
    
    Sorted by: ${args.sort} | Time: ${args.time_filter} | Type: ${args.type}
    
    ${searchResults}`
      },
    })
  • Zod schema defining the input parameters for the search_reddit tool.
    parameters: z.object({
      query: z.string().describe("Search query"),
      subreddit: z.string().optional().describe("Limit search to specific subreddit (without r/ prefix)"),
      sort: z.enum(["relevance", "hot", "top", "new", "comments"]).default("relevance").describe("Sort order"),
      time_filter: z.enum(["hour", "day", "week", "month", "year", "all"]).default("all").describe("Time filter"),
      limit: z.number().min(1).max(100).default(10).describe("Number of results"),
      type: z.enum(["link", "sr", "user"]).default("link").describe("Type of content to search"),
    }),
  • The core handler function in RedditClient that executes the Reddit API search request, handles authentication, constructs query parameters, fetches results, and maps to RedditPost objects.
    async searchReddit(
      query: string,
      options: {
        subreddit?: string
        sort?: string
        timeFilter?: string
        limit?: number
        type?: string
      } = {},
    ): Promise<RedditPost[]> {
      await this.authenticate()
      try {
        const { subreddit, sort = "relevance", timeFilter = "all", limit = 25, type = "link" } = options
        const endpoint = subreddit ? `/r/${subreddit}/search.json` : "/search.json"
    
        const params = new URLSearchParams({
          q: query,
          sort,
          t: timeFilter,
          limit: limit.toString(),
          type,
          ...(subreddit && { restrict_sr: "true" }),
        })
    
        const response = await this.makeRequest(`${endpoint}?${params}`)
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`)
        }
    
        const json = (await response.json()) as { data: { children: any[] } }
    
        return json.data.children
          .filter((child: any) => child.kind === "t3") // Only posts
          .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 ?? undefined,
              permalink: post.permalink,
            }
          })
      } catch {
        throw new Error(`Failed to search Reddit for: ${query}`)
      }
    }
  • The MCP tool's execute handler that validates input, calls the RedditClient.searchReddit helper, and formats the markdown search results output.
      execute: async (args) => {
        const client = getRedditClient()
        if (!client) {
          throw new Error("Reddit client not initialized")
        }
    
        if (!args.query || args.query.trim() === "") {
          throw new Error("Search query cannot be empty")
        }
    
        const posts = await client.searchReddit(args.query, {
          subreddit: args.subreddit,
          sort: args.sort,
          timeFilter: args.time_filter,
          limit: args.limit,
          type: args.type,
        })
    
        if (posts.length === 0) {
          const searchLocation = args.subreddit ? ` in r/${args.subreddit}` : ""
          return `No results found for "${args.query}"${searchLocation}.`
        }
    
        const searchResults = posts
          .map((post, index) => {
            const flags = [...(post.over18 ? ["**NSFW**"] : []), ...(post.spoiler ? ["**Spoiler**"] : [])]
    
            return `### ${index + 1}. ${post.title} ${flags.join(" ")}
    - Subreddit: r/${post.subreddit}
    - Author: u/${post.author}
    - Score: ${post.score.toLocaleString()} (${(post.upvoteRatio * 100).toFixed(1)}% upvoted)
    - Comments: ${post.numComments.toLocaleString()}
    - Posted: ${new Date(post.createdUtc * 1000).toLocaleString()}
    - Link: https://reddit.com${post.permalink}`
          })
          .join("\n\n")
    
        const searchLocation = args.subreddit ? ` in r/${args.subreddit}` : ""
        return `# Reddit Search Results for: "${args.query}"${searchLocation}
    
    Sorted by: ${args.sort} | Time: ${args.time_filter} | Type: ${args.type}
    
    ${searchResults}`
      },
    })
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. 'Search for posts' implies a read-only operation, but it doesn't mention rate limits, authentication needs, pagination behavior, or what happens when no results are found. For a search tool with zero annotation coverage, this leaves significant gaps in understanding how the tool behaves.

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 gets straight to the point with zero wasted words. It's appropriately sized for a search tool and front-loads the core functionality without unnecessary elaboration.

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 search tool with 6 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain what the search returns (e.g., post metadata, content snippets), error conditions, or how results are structured. The agent must rely entirely on the input schema for parameter details without contextual guidance.

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%, with all 6 parameters well-documented in the schema itself (e.g., 'limit' with min/max, 'sort' with enum values). The description adds no parameter information beyond what's in the schema, so it meets the baseline for high schema coverage without compensating value.

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 'Search for posts on Reddit' clearly states the verb ('Search') and resource ('posts on Reddit'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'get_top_posts' or 'get_reddit_post' that also retrieve posts, missing full sibling distinction.

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_top_posts' (for trending content) or 'get_reddit_post' (for specific posts). There's no mention of prerequisites, context, or exclusions, 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

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

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