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
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Maximum number of results to return | |
| query | Yes | The search query | |
| sort | No | Sort order: relevance, hot, top, new, comments | relevance |
| subreddit | No | Search within a specific subreddit (optional) | |
| time_filter | No | Time filter: hour, day, week, month, year, all | all |
| type | No | Type 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}` }, })
- src/index.ts:442-449 (schema)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"), }),
- src/client/reddit-client.ts:548-605 (handler)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}`) } }
- src/index.ts:450-494 (helper)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}` }, })