UNPKG

rednote-mcp

Version:

A friendly tool to help you access and interact with Xiaohongshu (RedNote) content through Model Context Protocol.

252 lines (250 loc) 9.42 kB
#!/usr/bin/env node "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js"); const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js"); const zod_1 = require("zod"); const authManager_1 = require("./auth/authManager"); const rednoteTools_1 = require("./tools/rednoteTools"); const logger_1 = __importStar(require("./utils/logger")); const child_process_1 = require("child_process"); const util_1 = require("util"); const stdioLogger_1 = require("./utils/stdioLogger"); const execAsync = (0, util_1.promisify)(child_process_1.exec); const name = 'rednote'; const description = 'A friendly tool to help you access and interact with Xiaohongshu (RedNote) content through Model Context Protocol.'; const version = '0.2.3'; // Create server instance const server = new mcp_js_1.McpServer({ name, version, protocolVersion: '2024-11-05', capabilities: { tools: true, sampling: {}, roots: { listChanged: true } } }); // Register tools server.tool('search_notes', '根据关键词搜索笔记', { keywords: zod_1.z.string().describe('搜索关键词'), limit: zod_1.z.number().optional().describe('返回结果数量限制') }, async ({ keywords, limit = 10 }) => { logger_1.default.info(`Searching notes with keywords: ${keywords}, limit: ${limit}`); try { const tools = new rednoteTools_1.RedNoteTools(); const notes = await tools.searchNotes(keywords, limit); logger_1.default.info(`Found ${notes.length} notes`); return { content: notes.map((note) => ({ type: 'text', text: `标题: ${note.title}\n作者: ${note.author}\n内容: ${note.content}\n点赞: ${note.likes}\n评论: ${note.comments}\n链接: ${note.url}\n---` })) }; } catch (error) { logger_1.default.error('Error searching notes:', error); throw error; } }); server.tool('get_note_content', '获取笔记内容', { url: zod_1.z.string().describe('笔记 URL') }, async ({ url }) => { logger_1.default.info(`Getting note content for URL: ${url}`); try { const tools = new rednoteTools_1.RedNoteTools(); const note = await tools.getNoteContent(url); logger_1.default.info(`Successfully retrieved note: ${note.title}`); return { content: [ { type: 'text', text: JSON.stringify(note) } ] }; } catch (error) { logger_1.default.error('Error getting note content:', error); throw error; } }); server.tool('get_note_comments', '获取笔记评论', { url: zod_1.z.string().describe('笔记 URL') }, async ({ url }) => { logger_1.default.info(`Getting comments for URL: ${url}`); try { const tools = new rednoteTools_1.RedNoteTools(); const comments = await tools.getNoteComments(url); logger_1.default.info(`Found ${comments.length} comments`); return { content: comments.map((comment) => ({ type: 'text', text: `作者: ${comment.author}\n内容: ${comment.content}\n点赞: ${comment.likes}\n时间: ${comment.time}\n---` })) }; } catch (error) { logger_1.default.error('Error getting note comments:', error); throw error; } }); // Add login tool server.tool('login', '登录小红书账号', {}, async () => { logger_1.default.info('Starting login process'); const authManager = new authManager_1.AuthManager(); try { await authManager.login(); logger_1.default.info('Login successful'); return { content: [ { type: 'text', text: '登录成功!Cookie 已保存。' } ] }; } catch (error) { logger_1.default.error('Login failed:', error); throw error; } finally { await authManager.cleanup(); } }); // Start the server async function main() { logger_1.default.info('Starting RedNote MCP Server'); // Start stdio logging const stopLogging = (0, stdioLogger_1.createStdioLogger)(`${logger_1.LOGS_DIR}/stdio.log`); const transport = new stdio_js_1.StdioServerTransport(); await server.connect(transport); logger_1.default.info('RedNote MCP Server running on stdio'); // Cleanup on process exit process.on('exit', () => { stopLogging(); }); } // 检查是否在 stdio 模式下运行 if (process.argv.includes('--stdio')) { main().catch((error) => { logger_1.default.error('Fatal error in main():', error); process.exit(1); }); } else { const { Command } = require('commander'); const program = new Command(); program.name(name).description(description).version(version); program .command('init [timeout]') .description('Initialize and login to RedNote') .argument('[timeout]', 'Login timeout in seconds', (value) => parseInt(value, 10), 10) .usage('[options] [timeout]') .addHelpText('after', ` Examples: $ rednote-mcp init # Login with default 10 seconds timeout $ rednote-mcp init 30 # Login with 30 seconds timeout $ rednote-mcp init --help # Display help information Notes: This command will launch a browser and open the RedNote login page. Please complete the login in the opened browser window. After successful login, the cookies will be automatically saved for future operations. The [timeout] parameter specifies the maximum waiting time (in seconds) for login, default is 10 seconds. The command will fail if the login is not completed within the specified timeout period.`) .action(async (timeout) => { logger_1.default.info(`Starting initialization process with timeout: ${timeout}s`); try { const authManager = new authManager_1.AuthManager(); await authManager.login({ timeout }); await authManager.cleanup(); logger_1.default.info('Initialization successful'); console.log('Login successful! Cookie has been saved.'); process.exit(0); } catch (error) { logger_1.default.error('Error during initialization:', error); console.error('Error during initialization:', error); process.exit(1); } }); program .command('pack-logs') .description('Pack all log files into a zip file') .action(async () => { try { const zipPath = await (0, logger_1.packLogs)(); console.log(`日志已打包到: ${zipPath}`); process.exit(0); } catch (error) { console.error('打包日志失败:', error); process.exit(1); } }); program .command('open-logs') .description('Open the logs directory in file explorer') .action(async () => { try { let command; switch (process.platform) { case 'darwin': // macOS command = `open "${logger_1.LOGS_DIR}"`; break; case 'win32': // Windows command = `explorer "${logger_1.LOGS_DIR}"`; break; case 'linux': // Linux command = `xdg-open "${logger_1.LOGS_DIR}"`; break; default: throw new Error(`Unsupported platform: ${process.platform}`); } await execAsync(command); console.log(`日志目录已打开: ${logger_1.LOGS_DIR}`); process.exit(0); } catch (error) { console.error('打开日志目录失败:', error); process.exit(1); } }); program.parse(process.argv); }