Skip to main content
Glama
jeebus87

reddirect

by jeebus87

Search Reddit

search_reddit

Search Reddit globally or within a specific subreddit. Filter results by sort order, time range, and number of posts.

Instructions

Search Reddit globally or within a specific subreddit. Returns matching posts.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query
subredditNoLimit search to a specific subreddit (without r/ prefix)
sortNoSort order for resultsrelevance
timeNoTime range filterall
limitNoNumber of results to return

Implementation Reference

  • The 'register' function registers the 'search_reddit' tool on the McpServer, defining its schema and handler.
    export function register(server: McpServer, client: RedditClient): void {
      server.registerTool(
        "search_reddit",
        {
          title: "Search Reddit",
          description:
            "Search Reddit globally or within a specific subreddit. Returns matching posts.",
          inputSchema: z.object({
            query: z.string().describe("Search query"),
            subreddit: z
              .string()
              .optional()
              .describe("Limit search to a specific subreddit (without r/ prefix)"),
            sort: z
              .enum(["relevance", "hot", "top", "new", "comments"])
              .default("relevance")
              .describe("Sort order for results"),
            time: z
              .enum(["hour", "day", "week", "month", "year", "all"])
              .default("all")
              .describe("Time range filter"),
            limit: z
              .number()
              .int()
              .min(1)
              .max(100)
              .default(25)
              .describe("Number of results to return"),
          }),
        },
        async ({ query, subreddit, sort, time, limit }) => {
          try {
            const params = new URLSearchParams({
              q: query,
              sort,
              t: time,
              limit: String(limit),
              type: "link",
            });
            if (subreddit) {
              params.set("restrict_sr", "on");
            }
    
            const basePath = subreddit
              ? `/r/${subreddit}/search.json`
              : `/search.json`;
    
            const data = await client.getJson(`${basePath}?${params}`);
            const results = (data?.data?.children || []).map((c: any) => {
              const p = c.data;
              return {
                id: p.name || `t3_${p.id}`,
                title: p.title,
                author: p.author,
                subreddit: p.subreddit,
                score: p.score,
                numComments: p.num_comments,
                url: p.url,
                permalink: `${BASE_URL}${p.permalink}`,
                createdUtc: p.created_utc,
                isSelf: p.is_self,
                flair: p.link_flair_text || null,
              };
            });
    
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(
                    { query, subreddit: subreddit ?? null, sort, time, results },
                    null,
                    2
                  ),
                },
              ],
            };
          } catch (error) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Error searching Reddit: ${error instanceof Error ? error.message : String(error)}`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • Input schema for search_reddit: query (string, required), subreddit (string, optional), sort (enum with default 'relevance'), time (enum with default 'all'), limit (number 1-100, default 25).
    {
      title: "Search Reddit",
      description:
        "Search Reddit globally or within a specific subreddit. Returns matching posts.",
      inputSchema: z.object({
        query: z.string().describe("Search query"),
        subreddit: z
          .string()
          .optional()
          .describe("Limit search to a specific subreddit (without r/ prefix)"),
        sort: z
          .enum(["relevance", "hot", "top", "new", "comments"])
          .default("relevance")
          .describe("Sort order for results"),
        time: z
          .enum(["hour", "day", "week", "month", "year", "all"])
          .default("all")
          .describe("Time range filter"),
        limit: z
          .number()
          .int()
          .min(1)
          .max(100)
          .default(25)
          .describe("Number of results to return"),
      }),
  • The handler function executes the search logic: builds query params, calls Reddit API via client.getJson(), maps results to a structured response, and handles errors.
    async ({ query, subreddit, sort, time, limit }) => {
      try {
        const params = new URLSearchParams({
          q: query,
          sort,
          t: time,
          limit: String(limit),
          type: "link",
        });
        if (subreddit) {
          params.set("restrict_sr", "on");
        }
    
        const basePath = subreddit
          ? `/r/${subreddit}/search.json`
          : `/search.json`;
    
        const data = await client.getJson(`${basePath}?${params}`);
        const results = (data?.data?.children || []).map((c: any) => {
          const p = c.data;
          return {
            id: p.name || `t3_${p.id}`,
            title: p.title,
            author: p.author,
            subreddit: p.subreddit,
            score: p.score,
            numComments: p.num_comments,
            url: p.url,
            permalink: `${BASE_URL}${p.permalink}`,
            createdUtc: p.created_utc,
            isSelf: p.is_self,
            flair: p.link_flair_text || null,
          };
        });
    
        return {
          content: [
            {
              type: "text" as const,
              text: JSON.stringify(
                { query, subreddit: subreddit ?? null, sort, time, results },
                null,
                2
              ),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text" as const,
              text: `Error searching Reddit: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
          isError: true,
        };
      }
    }
  • The getJson method on RedditClient used by the search handler to fetch and parse JSON from the Reddit API.
    async getJson(endpoint: string): Promise<any> {
      const res = await this.get(endpoint);
      if (res.status === 401) {
        // Token expired, retry
        this.session = null;
        await this.ensureToken();
        const retry = await this.get(endpoint);
        return retry.json();
      }
      return res.json();
    }
  • src/index.ts:8-8 (registration)
    Entry point imports registerSearchTools from search.ts (line 8) and calls it on line 28 to register the tool.
    import { register as registerSearchTools } from "./tools/search.js";
Behavior2/5

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

No annotations provided, so description must convey behavioral traits. It only states 'Returns matching posts' without details on pagination, rate limits, or authentication needs. This is insufficient.

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?

Two sentences, 12 words, front-loaded with purpose. No superfluous content.

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?

No output schema, yet description does not explain return format (e.g., what fields are in 'matching posts'). Additional details on result structure or pagination would improve completeness.

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 coverage is 100%, so parameters are already documented. The description adds context for global vs subreddit search but no further semantic meaning beyond the schema. Baseline 3 is appropriate.

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 'Search Reddit globally or within a specific subreddit. Returns matching posts.' This uses specific verbs and resources, and distinguishes from siblings like browse_subreddit.

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 on when to use this tool vs alternatives such as browse_subreddit or get_subreddit_info. The description lacks context on appropriate usage scenarios.

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/jeebus87/reddirect'

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