demo-advanced.js•6.58 kB
#!/usr/bin/env node
import { spawn } from 'child_process';
import fs from 'fs-extra';
import path from 'path';
import os from 'os';
class TafaMcpAdvancedDemo {
constructor() {
this.testDir = path.join(os.tmpdir(), 'tafa-mcp-advanced-demo');
this.server = null;
this.requestId = 1;
}
async runDemo() {
console.log('🚀 Tafa MCP Advanced Features Demo');
console.log('===================================\n');
// Setup test environment
await this.setupTestEnv();
// Start server
await this.startServer();
// Run demonstration
await this.runAdvancedDemo();
// Cleanup
await this.cleanup();
}
async setupTestEnv() {
console.log('🔧 Setting up advanced demo environment...');
await fs.ensureDir(this.testDir);
// Create various file types
await fs.writeFile(path.join(this.testDir, 'document.txt'), 'Important document content');
await fs.writeFile(path.join(this.testDir, 'script.js'), 'console.log("Hello World");');
await fs.writeFile(path.join(this.testDir, 'style.css'), 'body { margin: 0; }');
await fs.writeFile(path.join(this.testDir, 'data.json'), JSON.stringify({name: 'demo', version: '1.0'}));
// Create duplicate files
await fs.writeFile(path.join(this.testDir, 'duplicate1.txt'), 'Same content');
await fs.writeFile(path.join(this.testDir, 'duplicate2.txt'), 'Same content');
// Create some old files for batch rename
await fs.writeFile(path.join(this.testDir, 'old_file1.txt'), 'Old file 1');
await fs.writeFile(path.join(this.testDir, 'old_file2.txt'), 'Old file 2');
// Create subdirectory
await fs.ensureDir(path.join(this.testDir, 'projects'));
await fs.writeFile(path.join(this.testDir, 'projects', 'project1.md'), '# Project 1');
console.log(`✅ Advanced demo environment ready at: ${this.testDir}\n`);
}
async startServer() {
return new Promise((resolve, reject) => {
console.log('🚀 Starting Tafa MCP Server...');
this.server = spawn('node', ['src/index.js', this.testDir], {
stdio: ['pipe', 'pipe', 'pipe'],
cwd: process.cwd()
});
this.server.stdout.on('data', (data) => {
const output = data.toString();
if (output.includes('Tafa MCP Server connected and ready')) {
console.log('✅ Server started successfully!\n');
resolve();
}
});
this.server.stderr.on('data', (data) => {
console.error('❌ Server error:', data.toString());
});
setTimeout(() => {
reject(new Error('Server startup timeout'));
}, 10000);
});
}
async runAdvancedDemo() {
console.log('🎬 Advanced Demo Sequence Starting...\n');
// 1. Show initial directory structure
await this.sendRequest('list_directory', {
path: this.testDir,
recursive: true,
showHidden: false
}, '📁 Initial Directory Structure');
// 2. Find duplicate files
await this.sendRequest('find_duplicates', {
directory: this.testDir,
minSize: 0
}, '🔍 Finding Duplicate Files');
// 3. Organize files by extension
await this.sendRequest('organize_files', {
directory: this.testDir,
organizationType: 'extension'
}, '📂 Organizing Files by Extension');
// 4. Show organized structure
await this.sendRequest('list_directory', {
path: this.testDir,
recursive: true,
showHidden: false
}, '📁 Organized Directory Structure');
// 5. Batch rename files
await this.sendRequest('batch_rename', {
directory: path.join(this.testDir, '.txt'),
pattern: 'old_',
replacement: 'new_'
}, '🔄 Batch Renaming Files');
// 6. Create archive
await this.sendRequest('compress_files', {
sourcePaths: [
path.join(this.testDir, '.txt'),
path.join(this.testDir, '.js')
],
destinationPath: path.join(this.testDir, 'backup.zip'),
format: 'zip'
}, '📦 Creating Archive');
// 7. Extract archive to new location
await fs.ensureDir(path.join(this.testDir, 'extracted'));
await this.sendRequest('extract_archive', {
archivePath: path.join(this.testDir, 'backup.zip'),
destinationPath: path.join(this.testDir, 'extracted')
}, '📤 Extracting Archive');
// 8. Final directory listing
await this.sendRequest('list_directory', {
path: this.testDir,
recursive: true,
showHidden: false
}, '📁 Final Directory Structure');
console.log('🎉 Advanced demo sequence completed successfully!\n');
}
async sendRequest(tool, params, description) {
return new Promise((resolve, reject) => {
console.log(`${description}:`);
console.log(`🔧 Calling: ${tool}`);
const request = {
jsonrpc: '2.0',
id: this.requestId++,
method: 'tools/call',
params: {
name: tool,
arguments: params
}
};
// Set up response handler
const responseHandler = (data) => {
try {
const lines = data.toString().split('\n').filter(line => line.trim());
for (const line of lines) {
if (line.startsWith('{') && line.includes('"result"')) {
const response = JSON.parse(line);
if (response.id === request.id) {
console.log('📤 Response:', response.result.content[0].text);
console.log(''); // Empty line for spacing
this.server.stdout.removeListener('data', responseHandler);
resolve(response);
return;
}
}
}
} catch (error) {
console.error('❌ Error parsing response:', error.message);
this.server.stdout.removeListener('data', responseHandler);
reject(error);
}
};
this.server.stdout.on('data', responseHandler);
this.server.stdin.write(JSON.stringify(request) + '\n');
// Timeout after 10 seconds
setTimeout(() => {
this.server.stdout.removeListener('data', responseHandler);
reject(new Error('Request timeout'));
}, 10000);
});
}
async cleanup() {
console.log('🧹 Cleaning up...');
if (this.server) {
this.server.kill();
}
await fs.remove(this.testDir);
console.log('✅ Advanced demo complete!');
}
}
// Run demo
const demo = new TafaMcpAdvancedDemo();
demo.runDemo().catch(console.error);