test.js•7.52 kB
#!/usr/bin/env node
/**
* Test script for Enhanced Calibre RAG MCP Server
* Tests basic functionality and RAG capabilities
*/
const { spawn } = require('child_process');
const path = require('path');
class MCPTester {
constructor() {
this.server = null;
this.requestId = 1;
}
generateId() {
return this.requestId++;
}
sendRequest(method, params = {}) {
return new Promise((resolve, reject) => {
const id = this.generateId();
const request = {
jsonrpc: '2.0',
id: id,
method: method,
params: params
};
console.log(`→ ${JSON.stringify(request)}`);
this.server.stdin.write(JSON.stringify(request) + '\n');
const timeout = setTimeout(() => {
reject(new Error('Request timeout'));
}, 10000);
const responseHandler = (data) => {
const lines = data.toString().split('\n');
for (const line of lines) {
if (line.trim()) {
try {
const response = JSON.parse(line);
if (response.id === id) {
clearTimeout(timeout);
this.server.stdout.removeListener('data', responseHandler);
console.log(`← ${JSON.stringify(response, null, 2)}`);
if (response.error) {
reject(new Error(response.error.message));
} else {
resolve(response.result);
}
return;
}
} catch (error) {
// Ignore parse errors for partial responses
}
}
}
};
this.server.stdout.on('data', responseHandler);
});
}
async startServer() {
console.log('🚀 Starting Enhanced Calibre RAG MCP Server...');
this.server = spawn('node', ['server.js'], {
stdio: 'pipe',
cwd: __dirname
});
this.server.stderr.on('data', (data) => {
console.log(`[Server Log] ${data.toString().trim()}`);
});
this.server.on('error', (error) => {
console.error('❌ Server error:', error);
});
// Wait a moment for server to start
await new Promise(resolve => setTimeout(resolve, 1000));
}
async stopServer() {
if (this.server) {
this.server.kill();
console.log('🛑 Server stopped');
}
}
async runTests() {
try {
await this.startServer();
console.log('\n📋 Running test suite...\n');
// Test 1: Initialize
console.log('1️⃣ Testing initialization...');
const initResult = await this.sendRequest('initialize');
console.log('✅ Initialization successful\n');
// Test 2: List tools
console.log('2️⃣ Testing tools list...');
const toolsResult = await this.sendRequest('tools/list');
console.log(`✅ Found ${toolsResult.tools.length} tools\n`);
// Test 3: List projects (should be empty initially)
console.log('3️⃣ Testing list projects...');
try {
const projectsResult = await this.sendRequest('tools/call', {
name: 'list_projects',
arguments: {}
});
console.log('✅ List projects successful\n');
} catch (error) {
console.log(`⚠️ List projects: ${error.message}\n`);
}
// Test 4: Create test project
console.log('4️⃣ Testing project creation...');
try {
const createResult = await this.sendRequest('tools/call', {
name: 'create_project',
arguments: {
name: 'test_project_' + Date.now(),
description: 'Test project for RAG functionality'
}
});
console.log('✅ Project creation successful\n');
} catch (error) {
console.log(`⚠️ Project creation: ${error.message}\n`);
}
// Test 5: Search books
console.log('5️⃣ Testing book search...');
try {
const searchResult = await this.sendRequest('tools/call', {
name: 'search',
arguments: {
query: 'python',
limit: 5
}
});
console.log('✅ Book search successful\n');
} catch (error) {
console.log(`⚠️ Book search: ${error.message}\n`);
}
// Test 6: Test embeddings capability
console.log('6️⃣ Testing embeddings initialization...');
// This would be tested through the add_books_to_project tool
// but requires actual books in the library
console.log('ℹ️ Embeddings test requires books in library\n');
console.log('🎉 Test suite completed!');
console.log('\n📝 Next steps:');
console.log(' 1. Add books to your Calibre library');
console.log(' 2. Search for books using the search tool');
console.log(' 3. Create a project and add books to it');
console.log(' 4. Use search_project_context for RAG queries');
} catch (error) {
console.error('❌ Test failed:', error);
} finally {
await this.stopServer();
}
}
}
// Configuration check
function checkConfiguration() {
console.log('🔍 Checking configuration...\n');
const fs = require('fs');
// Check if server.js exists
if (!fs.existsSync('server.js')) {
console.error('❌ server.js not found');
process.exit(1);
}
// Check if package.json exists
if (!fs.existsSync('package.json')) {
console.error('❌ package.json not found');
process.exit(1);
}
// Check if node_modules exists
if (!fs.existsSync('node_modules')) {
console.log('⚠️ node_modules not found. Run: npm install');
console.log(' Installing dependencies...');
const { execSync } = require('child_process');
try {
execSync('npm install', { stdio: 'inherit' });
console.log('✅ Dependencies installed\n');
} catch (error) {
console.error('❌ Failed to install dependencies');
console.log(' Please run: npm install');
process.exit(1);
}
}
console.log('✅ Configuration check passed\n');
}
// Run tests
async function main() {
console.log('🧪 Enhanced Calibre RAG MCP Server Test Suite\n');
checkConfiguration();
const tester = new MCPTester();
await tester.runTests();
}
if (require.main === module) {
main().catch(console.error);
}
module.exports = MCPTester;