xiaohongshu-mcp-server
Version:
小红书 MCP 服务器 - 支持评论发布、内容获取等功能
215 lines (181 loc) • 6.03 kB
JavaScript
const { spawn, execSync } = require('child_process');
const path = require('path');
const fs = require('fs');
const os = require('os');
// 获取包的根目录和配置
const packageRoot = path.dirname(__dirname);
const configDir = path.join(os.homedir(), '.xiaohongshu-mcp');
const configFile = path.join(configDir, 'config.json');
// 读取配置
function loadConfig() {
if (fs.existsSync(configFile)) {
try {
return JSON.parse(fs.readFileSync(configFile, 'utf8'));
} catch (error) {
console.error('⚠️ 配置文件读取失败,使用默认配置');
}
}
// 默认配置
return {
pythonCommand: 'python3',
installPath: packageRoot,
logLevel: 'INFO',
dataDir: path.join(configDir, 'data')
};
}
// 检查 Python 是否安装
function checkPython() {
return new Promise((resolve) => {
const python = spawn('python', ['--version']);
python.on('close', (code) => {
if (code === 0) {
resolve('python');
} else {
// 尝试 python3
const python3 = spawn('python3', ['--version']);
python3.on('close', (code) => {
resolve(code === 0 ? 'python3' : null);
});
}
});
});
}
// 检查依赖是否安装
function checkDependencies() {
const requirementsPath = path.join(packageRoot, 'requirements.txt');
if (!fs.existsSync(requirementsPath)) {
console.error('❌ requirements.txt 文件不存在');
return false;
}
// 这里可以添加更详细的依赖检查
return true;
}
// 启动 MCP 服务器
async function startServer(pythonCmd, config) {
console.log('🚀 启动小红书 MCP 服务器...');
console.log(`📁 工作目录: ${packageRoot}`);
console.log(`🐍 Python 命令: ${pythonCmd}`);
const args = ['-m', 'src.interfaces.mcp.server'];
// 添加命令行参数
if (process.argv.includes('--dev')) {
args.push('--dev');
}
const server = spawn(pythonCmd, args, {
cwd: packageRoot,
stdio: 'inherit',
env: {
...process.env,
PYTHONPATH: packageRoot,
XIAOHONGSHU_DATA_DIR: config.dataDir,
XIAOHONGSHU_LOG_LEVEL: config.logLevel
}
});
server.on('error', (err) => {
console.error('❌ 启动服务器失败:', err.message);
process.exit(1);
});
server.on('close', (code) => {
console.log(`🔚 服务器退出,代码: ${code}`);
process.exit(code);
});
// 处理进程信号
process.on('SIGINT', () => {
console.log('\n🛑 收到中断信号,正在关闭服务器...');
server.kill('SIGINT');
});
process.on('SIGTERM', () => {
console.log('\n🛑 收到终止信号,正在关闭服务器...');
server.kill('SIGTERM');
});
}
// 安装 Python 依赖
async function installDependencies(pythonCmd) {
return new Promise((resolve, reject) => {
console.log('📦 正在安装 Python 依赖...');
const requirementsPath = path.join(packageRoot, 'requirements.txt');
const pip = spawn(pythonCmd, ['-m', 'pip', 'install', '-r', requirementsPath], {
stdio: 'inherit'
});
pip.on('close', (code) => {
if (code === 0) {
console.log('✅ Python 依赖安装完成');
resolve();
} else {
reject(new Error('Python 依赖安装失败'));
}
});
});
}
// 主函数
async function main() {
try {
// 加载配置
const config = loadConfig();
console.log('🔍 检查运行环境...');
console.log(`📁 安装路径: ${config.installPath}`);
console.log(`📁 数据目录: ${config.dataDir}`);
// 检查 Python(使用配置中的命令)
let pythonCmd = config.pythonCommand;
// 验证配置的 Python 命令是否有效
try {
execSync(`${pythonCmd} --version`, { stdio: 'pipe' });
console.log(`✅ 使用配置的 Python: ${pythonCmd}`);
} catch (error) {
console.log(`⚠️ 配置的 Python 命令无效,重新检测...`);
pythonCmd = await checkPython();
if (!pythonCmd) {
console.error(`❌ 未找到 Python 环境
请安装 Python 3.8+ 后重新运行:
npm install -g xiaohongshu-mcp-server`);
process.exit(1);
}
}
// 检查依赖
if (!checkDependencies()) {
console.error('❌ 依赖检查失败');
process.exit(1);
}
// 启动服务器
await startServer(pythonCmd, config);
} catch (error) {
console.error('❌ 启动失败:', error.message);
console.log(`
💡 故障排除:
1. 确保已安装 Python 3.8+
2. 检查网络连接
3. 尝试重新安装:npm install -g xiaohongshu-mcp-server
4. 查看详细日志:xiaohongshu-mcp --dev
📞 获取帮助:https://github.com/yourusername/xiaohongshu-mcp-server/issues
`);
process.exit(1);
}
}
// 显示帮助信息
if (process.argv.includes('--help') || process.argv.includes('-h')) {
console.log(`
🔴 小红书 MCP 服务器
用法:
xiaohongshu-mcp [选项]
选项:
--dev 开发模式
--install-deps 强制重新安装依赖
--help, -h 显示帮助信息
示例:
xiaohongshu-mcp # 启动服务器
xiaohongshu-mcp --dev # 开发模式启动
xiaohongshu-mcp --install-deps # 重新安装依赖后启动
配置 CherryStudio:
在 CherryStudio 的 MCP 设置中添加:
{
"command": "xiaohongshu-mcp",
"args": []
}
`);
process.exit(0);
}
// 运行主函数
main().catch((error) => {
console.error('❌ 未处理的错误:', error);
process.exit(1);
});