Skip to main content
Glama

search_posts

Find Reddit posts in specific subreddits using search queries, with options to sort by relevance, newness, popularity, or top content and control result quantity.

Instructions

Rechercher des posts dans un subreddit

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
subredditYesLe nom du subreddit dans lequel rechercher
queryYesLa requête de recherche
sortNoMéthode de tri (relevance, new, hot, top)relevance
limitNoNombre de résultats à retourner

Implementation Reference

  • The main handler function for the 'search_posts' tool. It extracts parameters, retrieves the Reddit client, performs the search via client.searchPosts, formats the results using formatPostInfo, generates markdown summaries, and returns structured content.
    export async function searchPosts(params: {
      subreddit: string;
      query: string;
      sort?: string;
      limit?: number;
    }) {
      const { subreddit, query, sort = "relevance", limit = 25 } = params;
      const client = getRedditClient();
    
      if (!client) {
        throw new McpError(
          ErrorCode.InternalError,
          "Reddit client not initialized"
        );
      }
    
      try {
        console.log(`[Tool] Searching posts in r/${subreddit} for "${query}"`);
        const posts = await client.searchPosts(subreddit, query, sort, limit);
        const formattedPosts = posts.map(formatPostInfo);
    
        const postSummaries = formattedPosts
          .map(
            (post, index) => `
    ### ${index + 1}. ${post.title}
    - Auteur: u/${post.author}
    - Score: ${post.stats.score.toLocaleString()} (${(post.stats.upvoteRatio * 100).toFixed(1)}% positifs)
    - Commentaires: ${post.stats.comments.toLocaleString()}
    - Posté: ${post.metadata.posted}
    - Lien: ${post.links.shortLink}
        `
          )
          .join("\n");
    
        return {
          content: [
            {
              type: "text",
              text: `
    # Résultats de recherche dans r/${subreddit}
    
    **Requête:** "${query}"
    **Tri:** ${sort}
    **Résultats trouvés:** ${posts.length}
    
    ${postSummaries}
              `,
            },
          ],
        };
      } catch (error) {
        console.error(`[Error] Error searching posts: ${error}`);
        throw new McpError(
          ErrorCode.InternalError,
          `Failed to search posts: ${error}`
        );
      }
    }
  • The input schema definition and tool description for 'search_posts' provided to the MCP ListTools request handler.
    name: "search_posts",
    description: "Rechercher des posts dans un subreddit",
    inputSchema: {
      type: "object",
      properties: {
        subreddit: {
          type: "string",
          description: "Le nom du subreddit dans lequel rechercher",
        },
        query: {
          type: "string",
          description: "La requête de recherche",
        },
        sort: {
          type: "string",
          description: "Méthode de tri (relevance, new, hot, top)",
          enum: ["relevance", "new", "hot", "top"],
          default: "relevance",
        },
        limit: {
          type: "integer",
          description: "Nombre de résultats à retourner",
          default: 25,
        },
      },
      required: ["subreddit", "query"],
    },
  • src/index.ts:493-496 (registration)
    The switch case in the CallToolRequestHandler that registers and dispatches calls to the searchPosts handler function from tools.
    case "search_posts":
      return await tools.searchPosts(
        toolParams as { subreddit: string; query: string; sort?: string; limit?: number }
      );
  • The RedditClient helper method that performs the actual Reddit API search request and maps the response to RedditPost objects, used by the tool handler.
    async searchPosts(subreddit: string, query: string, sort: string = "relevance", limit: number = 25): Promise<RedditPost[]> {
      await this.authenticate();
      try {
        const response = await this.api.get(`/r/${subreddit}/search.json`, {
          params: {
            q: query,
            restrict_sr: true,
            sort,
            limit,
            type: "link"
          }
        });
    
        return response.data.data.children.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,
            permalink: post.permalink,
          };
        });
      } catch (error) {
        console.error(`[Error] Failed to search posts in ${subreddit}:`, error);
        throw new Error(`Failed to search posts in ${subreddit}`);
      }
    }
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. While 'Rechercher' implies a read operation, it doesn't specify authentication requirements, rate limits, pagination behavior, or what constitutes a 'post' in the return. For a search tool with 4 parameters, this leaves significant behavioral 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 a single, efficient sentence in French that directly states the tool's function without unnecessary words. It's appropriately sized for a search operation and front-loads the essential information.

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 4 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what constitutes a successful search, what format results return, or how to interpret empty results. The agent would need to guess about the tool's behavior and output structure.

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?

The description mentions 'dans un subreddit' which aligns with the 'subreddit' parameter, but adds no additional semantic context beyond what's already in the schema descriptions. With 100% schema description coverage, the baseline is 3 - the description doesn't compensate but doesn't need to since the schema is comprehensive.

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 action ('Rechercher') and target resource ('posts dans un subreddit'), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'search_subreddits' or 'get_top_posts', which would require more specific scope definition.

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' or 'search_subreddits'. There's no mention of prerequisites, context, or exclusion criteria, 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/samy-clivolt/reddit-mcp-server'

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