Skip to main content
Glama
hillaryTse

HackerNews MCP Server

by hillaryTse

search_posts

Search HackerNews posts using keywords with filters for content type, author, date ranges, points, and comments. Retrieve paginated results sorted by relevance or date.

Instructions

Search HackerNews posts by keywords with advanced filtering options. Supports filtering by content type (story, comment, poll, etc.), author, date ranges, points thresholds, and comment counts. Returns paginated results with metadata. Default sort is by relevance, but can sort chronologically with sortByDate=true.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryNo
tagsNo
authorNo
storyIdNo
minPointsNo
maxPointsNo
minCommentsNo
maxCommentsNo
dateAfterNo
dateBeforeNo
sortByDateNo
pageNo
hitsPerPageNo

Implementation Reference

  • The core handler function that implements the logic for the 'search_posts' tool. It parses and validates the input arguments, performs additional business logic validations, constructs search parameters, invokes the HackerNews API (with optional date sorting), and formats the paginated response.
    export async function handleSearchPosts(args: unknown) {
      // Validate input
      const parseResult = SearchPostsInputSchema.safeParse(args);
    
      if (!parseResult.success) {
        throw new ValidationError("Invalid search parameters", parseResult.error.errors);
      }
    
      const input: SearchPostsInput = parseResult.data;
    
      // Additional validation
      if (input.minPoints !== undefined && input.maxPoints !== undefined) {
        if (input.minPoints > input.maxPoints) {
          throw new ValidationError("minPoints cannot be greater than maxPoints");
        }
      }
    
      if (input.minComments !== undefined && input.maxComments !== undefined) {
        if (input.minComments > input.maxComments) {
          throw new ValidationError("minComments cannot be greater than maxComments");
        }
      }
    
      if (input.dateAfter && input.dateBefore) {
        const after = new Date(input.dateAfter);
        const before = new Date(input.dateBefore);
        if (after > before) {
          throw new ValidationError("dateAfter cannot be later than dateBefore");
        }
      }
    
      // Build API parameters
      const params = buildSearchParams(input);
    
      // Call appropriate API endpoint
      const result = input.sortByDate
        ? await apiClient.searchByDate(params)
        : await apiClient.search(params);
    
      // Format response with pagination metadata
      const response = {
        results: result.hits,
        pagination: {
          totalResults: result.nbHits,
          currentPage: result.page,
          totalPages: result.nbPages,
          resultsPerPage: result.hitsPerPage,
        },
        processingTimeMS: result.processingTimeMS,
        remainingQuota: apiClient.getRemainingQuota(),
      };
    
      return formatToolResponse(response);
    }
  • Zod schema defining the input structure and validation rules for the search_posts tool, including optional filters for query, tags, author, points, comments, dates, sorting, and pagination.
     * Schema for search_posts tool input
     */
    export const SearchPostsInputSchema = z.object({
      query: z.string().max(1000).optional(),
      tags: z
        .array(z.enum(["story", "comment", "poll", "pollopt", "show_hn", "ask_hn", "front_page"]))
        .optional(),
      author: z.string().min(1).max(15).optional(),
      storyId: z.number().int().positive().optional(),
      minPoints: z.number().int().nonnegative().optional(),
      maxPoints: z.number().int().nonnegative().optional(),
      minComments: z.number().int().nonnegative().optional(),
      maxComments: z.number().int().nonnegative().optional(),
      dateAfter: z.string().datetime().optional(),
      dateBefore: z.string().datetime().optional(),
      sortByDate: z.boolean().optional().default(false),
      page: z.number().int().nonnegative().max(999).optional().default(0),
      hitsPerPage: z.number().int().min(1).max(100).optional().default(20),
    });
    
    export type SearchPostsInput = z.infer<typeof SearchPostsInputSchema>;
  • Registration of the search_posts tool in the MCP tools list, providing name, description, and JSON schema for input validation in tool discovery.
    {
      name: "search_posts",
      description:
        "Search HackerNews posts by keywords with advanced filtering options. Supports filtering by content type (story, comment, poll, etc.), author, date ranges, points thresholds, and comment counts. Returns paginated results with metadata. Default sort is by relevance, but can sort chronologically with sortByDate=true.",
      inputSchema: zodToJsonSchema(SearchPostsInputSchema),
    },
  • src/index.ts:52-54 (registration)
    Dispatch/registration in the main MCP server request handler switch statement that routes 'search_posts' tool calls to the specific handler function.
    case "search_posts":
      return await handleSearchPosts(args);
  • Helper function that transforms SearchPostsInput into HN Algolia API search parameters, handling tags, numeric filters for points/comments/dates, and pagination.
    export function buildSearchParams(input: SearchPostsInput): {
      query?: string;
      tags?: string;
      numericFilters?: string;
      page?: number;
      hitsPerPage?: number;
    } {
      const params: {
        query?: string;
        tags?: string;
        numericFilters?: string;
        page?: number;
        hitsPerPage?: number;
      } = {};
    
      // Query string
      if (input.query) {
        params.query = input.query;
      }
    
      // Build tags array
      const tags: string[] = [];
    
      // Add content type tags
      if (input.tags && input.tags.length > 0) {
        tags.push(...input.tags);
      }
    
      // Add author tag
      if (input.author) {
        tags.push(`author_${input.author}`);
      }
    
      // Add story ID tag
      if (input.storyId) {
        tags.push(`story_${input.storyId}`);
      }
    
      if (tags.length > 0) {
        params.tags = formatTags(tags);
      }
    
      // Build numeric filters array
      const numericFilters: string[] = [];
    
      // Points filters
      if (input.minPoints !== undefined) {
        numericFilters.push(`points>=${input.minPoints}`);
      }
      if (input.maxPoints !== undefined) {
        numericFilters.push(`points<=${input.maxPoints}`);
      }
    
      // Comments filters
      if (input.minComments !== undefined) {
        numericFilters.push(`num_comments>=${input.minComments}`);
      }
      if (input.maxComments !== undefined) {
        numericFilters.push(`num_comments<=${input.maxComments}`);
      }
    
      // Date filters
      if (input.dateAfter) {
        const timestamp = dateToUnixTimestamp(input.dateAfter);
        numericFilters.push(`created_at_i>=${timestamp}`);
      }
      if (input.dateBefore) {
        const timestamp = dateToUnixTimestamp(input.dateBefore);
        numericFilters.push(`created_at_i<=${timestamp}`);
      }
    
      if (numericFilters.length > 0) {
        params.numericFilters = formatNumericFilters(numericFilters);
      }
    
      // Pagination
      if (input.page !== undefined) {
        params.page = input.page;
      }
      if (input.hitsPerPage !== undefined) {
        params.hitsPerPage = input.hitsPerPage;
      }
    
      return params;
    }
Behavior3/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 adds useful context such as pagination, default sort behavior, and the ability to sort chronologically, but it lacks details on rate limits, authentication needs, error handling, or what metadata is included in results. This leaves gaps for a tool with 13 parameters.

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 appropriately sized and front-loaded, starting with the core purpose and then detailing features in a logical flow. Every sentence adds value without redundancy, making it efficient and easy to parse for an AI agent.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (13 parameters, no annotations, no output schema), the description is moderately complete. It covers the tool's purpose, key parameters, and basic behaviors like pagination and sorting, but lacks details on output format, error cases, or full parameter explanations, which could hinder agent effectiveness.

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

Parameters4/5

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

The schema description coverage is 0%, so the description must compensate. It effectively adds meaning by listing key parameters (e.g., content type, author, date ranges, points thresholds, comment counts) and explaining sortByDate and pagination defaults. However, it does not cover all 13 parameters (e.g., storyId is not mentioned), slightly reducing completeness.

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 the tool's purpose with specific verb ('Search') and resource ('HackerNews posts'), distinguishing it from sibling tools like get_front_page (which fetches a specific page) and get_post (which retrieves a single post). It explicitly mentions searching by keywords with advanced filtering, establishing a clear scope.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by mentioning 'advanced filtering options' and default behaviors like sorting by relevance, but it does not explicitly state when to use this tool versus alternatives like get_front_page or get_user. No exclusions or specific scenarios are provided, leaving some ambiguity for the agent.

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/hillaryTse/hn-mcp-server'

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