Skip to main content
Glama
Traves-Theberge

HackerNews MCP Server

Search Trending Topics

search_trending

Identify trending topics and keywords from top HackerNews posts by analyzing post trends and filtering by word length or post count.

Instructions

Find current trending topics and keywords from top HackerNews posts

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
minWordLengthNo
postCountNo

Implementation Reference

  • Implements the core logic for the 'search_trending' MCP tool: fetches the top HackerNews stories using hnClient.getTopStories(), retrieves details for the top N posts, filters valid story posts, extracts words from titles (lowercased, non-punctuation, length >= minWordLength, excluding common stopwords and numbers), counts word frequencies, and returns the top 20 trending words with counts and percentage of posts containing them, along with analysis summary.
    async ({ postCount, minWordLength }) => {
      try {
        const topStoryIds = await hnClient.getTopStories();
        const postsToAnalyze = topStoryIds.slice(0, postCount || 50);
        
        const posts = await hnClient.getMultipleItems(postsToAnalyze);
        const validPosts = posts.filter(post => post && post.title && post.type === "story");
    
        // Extract and count words from titles
        const wordCounts = new Map<string, number>();
        const commonWords = new Set(['the', 'and', 'for', 'are', 'but', 'not', 'you', 'all', 'can', 'had', 'her', 'was', 'one', 'our', 'out', 'day', 'get', 'has', 'him', 'his', 'how', 'its', 'may', 'new', 'now', 'old', 'see', 'two', 'way', 'who', 'boy', 'did', 'man', 'end', 'why', 'let', 'put', 'say', 'she', 'too', 'use']);
    
        validPosts.forEach(post => {
          if (post?.title) {
            const words = post.title.toLowerCase()
              .replace(/[^\w\s]/g, ' ')
              .split(/\s+/)
              .filter((word: string) => 
                word.length >= (minWordLength || 4) && 
                !commonWords.has(word) &&
                !/^\d+$/.test(word)
              );
    
            words.forEach((word: string) => {
              wordCounts.set(word, (wordCounts.get(word) || 0) + 1);
            });
          }
        });
    
        // Get top trending words
        const trendingTopics = Array.from(wordCounts.entries())
          .sort((a, b) => b[1] - a[1])
          .slice(0, 20)
          .map(([word, count]) => ({ word, count, percentage: ((count / validPosts.length) * 100).toFixed(1) }));
    
        return {
          content: [{
            type: "text",
            text: JSON.stringify({
              analysis_summary: {
                posts_analyzed: validPosts.length,
                total_unique_words: wordCounts.size,
                min_word_length: minWordLength
              },
              trending_topics: trendingTopics,
              timestamp: new Date().toISOString()
            }, null, 2)
          }]
        };
      } catch (error) {
        logger.error("Failed to get trending topics:", error);
        return {
          content: [{
            type: "text",
            text: `Error analyzing trending topics: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    }
  • Registers the 'search_trending' tool via server.registerTool() within the setupTools function, including title 'Search Trending Topics', description, and Zod inputSchema with optional postCount (10-100, default 50) and minWordLength (3-10, default 4) parameters, linking to the inline handler.
    // Search trending topics
    server.registerTool(
      "search_trending",
      {
        title: "Search Trending Topics",
        description: "Find current trending topics and keywords from top HackerNews posts",
        inputSchema: {
          postCount: z.number().min(10).max(100).default(50).optional(),
          minWordLength: z.number().min(3).max(10).default(4).optional()
        }
      },
      async ({ postCount, minWordLength }) => {
        try {
          const topStoryIds = await hnClient.getTopStories();
          const postsToAnalyze = topStoryIds.slice(0, postCount || 50);
          
          const posts = await hnClient.getMultipleItems(postsToAnalyze);
          const validPosts = posts.filter(post => post && post.title && post.type === "story");
    
          // Extract and count words from titles
          const wordCounts = new Map<string, number>();
          const commonWords = new Set(['the', 'and', 'for', 'are', 'but', 'not', 'you', 'all', 'can', 'had', 'her', 'was', 'one', 'our', 'out', 'day', 'get', 'has', 'him', 'his', 'how', 'its', 'may', 'new', 'now', 'old', 'see', 'two', 'way', 'who', 'boy', 'did', 'man', 'end', 'why', 'let', 'put', 'say', 'she', 'too', 'use']);
    
          validPosts.forEach(post => {
            if (post?.title) {
              const words = post.title.toLowerCase()
                .replace(/[^\w\s]/g, ' ')
                .split(/\s+/)
                .filter((word: string) => 
                  word.length >= (minWordLength || 4) && 
                  !commonWords.has(word) &&
                  !/^\d+$/.test(word)
                );
    
              words.forEach((word: string) => {
                wordCounts.set(word, (wordCounts.get(word) || 0) + 1);
              });
            }
          });
    
          // Get top trending words
          const trendingTopics = Array.from(wordCounts.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, 20)
            .map(([word, count]) => ({ word, count, percentage: ((count / validPosts.length) * 100).toFixed(1) }));
    
          return {
            content: [{
              type: "text",
              text: JSON.stringify({
                analysis_summary: {
                  posts_analyzed: validPosts.length,
                  total_unique_words: wordCounts.size,
                  min_word_length: minWordLength
                },
                trending_topics: trendingTopics,
                timestamp: new Date().toISOString()
              }, null, 2)
            }]
          };
        } catch (error) {
          logger.error("Failed to get trending topics:", error);
          return {
            content: [{
              type: "text",
              text: `Error analyzing trending topics: ${error instanceof Error ? error.message : String(error)}`
            }],
            isError: true
          };
        }
      }
    );
  • Input schema definition using Zod for the search_trending tool, specifying postCount: z.number().min(10).max(100).default(50).optional() and minWordLength: z.number().min(3).max(10).default(4).optional().
    {
      title: "Search Trending Topics",
      description: "Find current trending topics and keywords from top HackerNews posts",
      inputSchema: {
        postCount: z.number().min(10).max(100).default(50).optional(),
        minWordLength: z.number().min(3).max(10).default(4).optional()
      }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'current trending topics' and 'top HackerNews posts,' implying real-time data and a focus on popularity, but lacks details on rate limits, data freshness, authentication needs, or what constitutes 'trending.' This is a significant gap for a tool that likely involves external API calls.

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: 'Find current trending topics and keywords from top HackerNews posts.' It's front-loaded with the core purpose, has zero wasted words, and is appropriately sized for the tool's complexity. Every part of the sentence adds value.

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?

Given the tool's complexity (external data source, trending analysis), lack of annotations, no output schema, and 0% schema coverage, the description is incomplete. It doesn't cover parameter meanings, behavioral traits like rate limits, or output details (e.g., format of returned topics). This makes it inadequate for effective agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema has 0% description coverage, so the description must compensate for both parameters. It doesn't mention minWordLength or postCount at all, failing to explain their roles (e.g., filtering keywords by length or limiting posts analyzed). This leaves the agent guessing about parameter meanings beyond the schema's basic constraints.

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: 'Find current trending topics and keywords from top HackerNews posts.' It specifies the verb ('Find'), resource ('trending topics and keywords'), and source ('top HackerNews posts'), making the function unambiguous. However, it doesn't explicitly differentiate from sibling tools like search_posts or search_comments, which prevents a perfect score.

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. It doesn't mention when it's appropriate (e.g., for trend analysis vs. specific post searches) or when not to use it, nor does it reference sibling tools like search_posts or search_comments for comparison. This leaves the agent without context for tool selection.

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

Related 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/Traves-Theberge/Hackernews-MCP-Typescript'

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