/**
* search_comments MCP Tool
*/
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { HNError } from '../lib/errors.js';
import type { HNClient } from '../lib/hn-client.js';
import { createChildLogger } from '../lib/logger.js';
export function registerSearchComments(server: McpServer, hnClient: HNClient): void {
server.registerTool(
'search_comments',
{
title: 'Search Comments',
description: 'Search Hacker News comments by text content. Can filter by author or parent story.',
inputSchema: {
query: z.string().describe('Search query text'),
tags: z
.string()
.optional()
.describe("Optional filter tags. Examples: 'comment', 'author_USERNAME', 'story_ID'"),
sortByDate: z.boolean().optional().default(false).describe('Sort by date instead of relevance. Default: false'),
page: z.number().int().min(0).optional().default(0).describe('Page number (0-indexed)'),
hitsPerPage: z.number().int().min(1).max(100).optional().default(20).describe('Results per page'),
},
outputSchema: { hits: z.array(z.any()), nbHits: z.number(), nbPages: z.number() },
},
async ({ query, tags, sortByDate = false, page = 0, hitsPerPage = 20 }) => {
const correlationId = crypto.randomUUID();
const toolLogger = createChildLogger({ correlationId, tool: 'search_comments' });
try {
const searchTags = tags ? `${tags},comment` : 'comment';
toolLogger.info({ query, tags: searchTags, sortByDate, page, hitsPerPage }, 'Searching comments');
const searchFn = sortByDate ? hnClient.searchByDate.bind(hnClient) : hnClient.search.bind(hnClient);
const result = await searchFn({ query, tags: searchTags, page, hitsPerPage });
toolLogger.info({ nbHits: result.nbHits }, 'Search completed');
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
structuredContent: result as unknown as Record<string, unknown>,
};
} catch (error) {
toolLogger.error({ error }, 'Search failed');
if (error instanceof HNError) {
const errorContent = { error: error.message };
return {
content: [{ type: 'text', text: JSON.stringify(errorContent) }],
isError: true,
};
}
throw error;
}
}
);
}