# Directory Structure ``` ├── .gitignore ├── Claude.png ├── LICENSE ├── package-lock.json ├── package.json ├── README.md ├── src │ └── index.ts └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` # Dependencies node_modules/ npm-debug.log* yarn-debug.log* yarn-error.log* # Build output build/ dist/ *.tsbuildinfo # IDE and editor files .idea/ .vscode/ *.swp *.swo .DS_Store # Environment variables .env .env.local .env.*.local # Logs logs/ *.log # Test coverage coverage/ ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # Hacker News MCP Server A Model Context Protocol (MCP) server that provides tools for fetching stories from Hacker News. This server parses the HTML content from news.ycombinator.com and provides structured data for different types of stories (top, new, ask, show, jobs). <a href="https://glama.ai/mcp/servers/oge85xl22f"><img width="380" height="200" src="https://glama.ai/mcp/servers/oge85xl22f/badge" alt="Hacker News MCP server" /></a> ## Features - Fetch different types of stories (top, new, ask, show, jobs) - Get structured data including titles, URLs, points, authors, timestamps, and comment counts - Configurable limit on number of stories returned - Clean error handling and validation ## Installation 1. Clone the repository: ```bash git clone https://github.com/pskill9/hn-server cd hn-server ``` 2. Install dependencies: ```bash npm install ``` 3. Build the server: ```bash npm run build ``` 4. Add to your MCP settings configuration file (location depends on your system): For VSCode Claude extension: ```json { "mcpServers": { "hacker-news": { "command": "node", "args": ["/path/to/hn-server/build/index.js"] } } } ``` ## Usage The server provides a tool called `get_stories` that can be used to fetch stories from Hacker News. ### Tool: get_stories Parameters: - `type` (string): Type of stories to fetch - Options: 'top', 'new', 'ask', 'show', 'jobs' - Default: 'top' - `limit` (number): Number of stories to return - Range: 1-30 - Default: 10 Example usage: ```typescript use_mcp_tool with: server_name: "hacker-news" tool_name: "get_stories" arguments: { "type": "top", "limit": 5 } ``` Sample output: ```json [ { "title": "Example Story Title", "url": "https://example.com/story", "points": 100, "author": "username", "time": "2024-12-28T00:03:05", "commentCount": 50, "rank": 1 }, // ... more stories ] ``` ## Integrating with Claude To use this MCP server with Claude, you'll need to: 1. Have the Claude desktop app or VSCode Claude extension installed 2. Configure the MCP server in your settings 3. Use Claude's natural language interface to interact with Hacker News ### Configuration For the Claude desktop app, add the server configuration to: ```json // ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) // %APPDATA%\Claude\claude_desktop_config.json (Windows) { "mcpServers": { "hacker-news": { "command": "node", "args": ["/path/to/hn-server/build/index.js"] } } } ``` For the VSCode Claude extension, add to: ```json // VSCode Settings JSON { "mcpServers": { "hacker-news": { "command": "node", "args": ["/path/to/hn-server/build/index.js"] } } } ``` ### Example Interactions Once configured, you can interact with Claude using natural language to fetch Hacker News stories. Examples: - "Show me the top 5 stories from Hacker News" - "What are the latest Ask HN posts?" - "Get me the top Show HN submissions from today" Claude will automatically use the appropriate parameters to fetch the stories you want.  ### Story Object Structure Each story object contains: - `title` (string): The story title - `url` (string, optional): URL of the story (may be internal HN URL for text posts) - `points` (number): Number of upvotes - `author` (string): Username of the poster - `time` (string): Timestamp of when the story was posted - `commentCount` (number): Number of comments - `rank` (number): Position in the list ## Development The server is built using: - TypeScript - Model Context Protocol SDK - Axios for HTTP requests - Cheerio for HTML parsing To modify the server: 1. Make changes to `src/index.ts` 2. Rebuild: ```bash npm run build ``` ## Error Handling The server includes robust error handling for: - Invalid story types - Network failures - HTML parsing errors - Invalid parameter values Errors are returned with appropriate error codes and descriptive messages. ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. ## License MIT License - feel free to use this in your own projects. ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json { "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "outDir": "./build", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json { "name": "hn-server", "version": "0.1.0", "description": "MCP server for fetching and parsing Hacker News stories", "type": "module", "bin": { "hn-server": "./build/index.js" }, "files": [ "build" ], "scripts": { "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"", "prepare": "npm run build", "watch": "tsc --watch", "inspector": "npx @modelcontextprotocol/inspector build/index.js" }, "dependencies": { "@modelcontextprotocol/sdk": "0.6.0", "axios": "^1.7.9", "cheerio": "^1.0.0" }, "devDependencies": { "@types/node": "^20.11.24", "typescript": "^5.3.3" }, "keywords": [ "mcp", "model-context-protocol", "hacker-news", "hn", "news", "api", "scraper" ], "author": "Manav Kundra", "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/pskill9/hn-server.git" }, "bugs": { "url": "https://github.com/pskill9/hn-server/issues" }, "homepage": "https://github.com/pskill9/hn-server#readme" } ``` -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- ```typescript #!/usr/bin/env node import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from '@modelcontextprotocol/sdk/types.js'; import axios from 'axios'; import * as cheerio from 'cheerio'; interface Story { title: string; url?: string; points: number; author: string; time: string; commentCount: number; rank: number; } const isValidStoryType = (type: string): boolean => { return ['top', 'new', 'ask', 'show', 'jobs'].includes(type); }; class HackerNewsServer { private server: Server; private baseUrl = 'https://news.ycombinator.com'; constructor() { this.server = new Server( { name: 'hn-server', version: '0.1.0', }, { capabilities: { tools: {}, }, } ); this.setupToolHandlers(); // Error handling this.server.onerror = (error) => console.error('[MCP Error]', error); process.on('SIGINT', async () => { await this.server.close(); process.exit(0); }); } private async fetchStories(type: string = 'top'): Promise<Story[]> { try { const url = type === 'top' ? this.baseUrl : `${this.baseUrl}/${type}`; const response = await axios.get(url); const $ = cheerio.load(response.data); const stories: Story[] = []; $('.athing').each((i, elem) => { const titleRow = $(elem); const metadataRow = titleRow.next(); const rank = parseInt(titleRow.find('.rank').text(), 10); const titleElement = titleRow.find('.titleline > a').first(); const title = titleElement.text(); const url = titleElement.attr('href'); const sitebit = titleRow.find('.sitebit'); const points = parseInt(metadataRow.find('.score').text(), 10) || 0; const author = metadataRow.find('.hnuser').text(); const time = metadataRow.find('.age').attr('title') || ''; const commentText = metadataRow.find('a').last().text(); const commentCount = parseInt(commentText.split(' ')[0]) || 0; stories.push({ title, url: url?.startsWith('item?id=') ? `${this.baseUrl}/${url}` : url, points, author, time, commentCount, rank }); }); return stories; } catch (error) { if (axios.isAxiosError(error)) { throw new McpError( ErrorCode.InternalError, `Failed to fetch stories: ${error.message}` ); } throw error; } } private setupToolHandlers() { this.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: 'get_stories', description: 'Get stories from Hacker News', inputSchema: { type: 'object', properties: { type: { type: 'string', description: 'Type of stories to fetch (top, new, ask, show, jobs)', enum: ['top', 'new', 'ask', 'show', 'jobs'], default: 'top' }, limit: { type: 'number', description: 'Number of stories to return (max 30)', minimum: 1, maximum: 30, default: 10 } } } } ] })); this.server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name !== 'get_stories') { throw new McpError( ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}` ); } const args = request.params.arguments as { type?: string; limit?: number }; const type = args.type || 'top'; const limit = Math.min(args.limit || 10, 30); if (!isValidStoryType(type)) { throw new McpError( ErrorCode.InvalidParams, `Invalid story type: ${type}. Must be one of: top, new, ask, show, jobs` ); } try { const stories = await this.fetchStories(type); return { content: [ { type: 'text', text: JSON.stringify(stories.slice(0, limit), null, 2) } ] }; } catch (error) { if (error instanceof McpError) { throw error; } throw new McpError( ErrorCode.InternalError, `Failed to fetch stories: ${error}` ); } }); } async run() { const transport = new StdioServerTransport(); await this.server.connect(transport); console.error('Hacker News MCP server running on stdio'); } } const server = new HackerNewsServer(); server.run().catch(console.error); ```