#!/usr/bin/env node
/**
* Post-installation script for MCP Self-Learning Server
* Sets up directories, permissions, and initial configuration
*/
import fs from 'fs/promises';
import path from 'path';
import os from 'os';
async function postInstall() {
console.log('📦 Setting up MCP Self-Learning Server...\n');
try {
// Create system directories
await createDirectories();
// Set up configuration files
await setupConfiguration();
// Create systemd service if on Linux
if (os.platform() === 'linux') {
await createSystemdService();
}
console.log('✅ MCP Self-Learning Server setup complete!\n');
console.log('🚀 Quick start:');
console.log(' mcp-learn start # Start the MCP server');
console.log(' mcp-learn api # Start the REST API server');
console.log(' mcp-learn status # Check server status');
console.log(' mcp-learn health # Run health check\n');
} catch (error) {
console.error('❌ Setup failed:', error.message);
process.exit(1);
}
}
async function createDirectories() {
const homeDir = os.homedir();
const configDir = path.join(homeDir, '.mcp-learning');
const dataDir = path.join('/tmp', 'mcp-learning-shared'); // Fallback to /tmp for shared data
const directories = [
configDir,
path.join(configDir, 'logs'),
path.join(configDir, 'data'),
dataDir
];
console.log('📁 Creating directories...');
for (const dir of directories) {
try {
await fs.mkdir(dir, { recursive: true });
console.log(` ✓ ${dir}`);
} catch (error) {
if (error.code !== 'EEXIST') {
console.warn(` ⚠ Failed to create ${dir}: ${error.message}`);
}
}
}
}
async function setupConfiguration() {
const homeDir = os.homedir();
const configDir = path.join(homeDir, '.mcp-learning');
const configFile = path.join(configDir, 'config.json');
// Default configuration
const defaultConfig = {
version: '1.0.0',
server: {
port: 8765,
host: 'localhost',
autoStart: false
},
learning: {
maxMemorySize: 1000,
autoSaveInterval: 300000,
persistenceEnabled: true
},
api: {
authentication: false,
corsEnabled: true,
rateLimit: {
enabled: false,
max: 100,
windowMs: 900000
}
},
integrations: {
claudio: {
enabled: false,
path: '/home/ben/saralegui-solutions-llc/claude-assistant'
},
claudia: {
enabled: false,
path: '/home/ben/claudia'
}
},
logging: {
level: 'info',
console: true,
file: true
}
};
console.log('⚙️ Setting up configuration...');
try {
// Check if config already exists
await fs.access(configFile);
console.log(` ✓ Configuration exists at ${configFile}`);
} catch (error) {
// Create default config
await fs.writeFile(configFile, JSON.stringify(defaultConfig, null, 2));
console.log(` ✓ Created configuration at ${configFile}`);
}
}
async function createSystemdService() {
const homeDir = os.homedir();
const systemdDir = path.join(homeDir, '.config', 'systemd', 'user');
const serviceFile = path.join(systemdDir, 'mcp-self-learning.service');
// Find the installation path
const packagePath = process.cwd();
const nodePath = process.execPath;
const serviceContent = `[Unit]
Description=MCP Self-Learning Server
Documentation=https://github.com/saralegui-solutions/mcp-self-learning-server
After=network.target
Wants=network-online.target
StartLimitIntervalSec=300
StartLimitBurst=5
[Service]
Type=simple
WorkingDirectory=${packagePath}
Environment=HOME=${homeDir}
Environment=NODE_ENV=production
Environment=MCP_LEARN_AUTO_START=true
Environment=PATH=${path.dirname(nodePath)}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Main service command
ExecStart=${nodePath} ${path.join(packagePath, 'mcp-self-learning-server.js')}
# Service management
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
KillMode=mixed
KillSignal=SIGTERM
TimeoutStartSec=30
TimeoutStopSec=10
# Restart policy
Restart=on-failure
RestartSec=10
# Resource limits
LimitNOFILE=65536
LimitNPROC=4096
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=mcp-self-learning
[Install]
WantedBy=default.target
`;
console.log('🔧 Creating systemd service...');
try {
// Create systemd directory
await fs.mkdir(systemdDir, { recursive: true });
// Write service file
await fs.writeFile(serviceFile, serviceContent);
console.log(` ✓ Created systemd service at ${serviceFile}`);
console.log('\n🔧 To enable auto-start:');
console.log(' systemctl --user enable mcp-self-learning.service');
console.log(' systemctl --user start mcp-self-learning.service');
} catch (error) {
console.warn(` ⚠ Failed to create systemd service: ${error.message}`);
}
}
// Run post-install if this script is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
await postInstall();
}