#!/usr/bin/env node
const { spawn } = require('child_process');
const path = require('path');
async function testMCPStdioWithCorrectAuth() {
console.log('🧪 Testing MCP Anomaly Detection via stdio with correct credentials...\n');
// Start the MCP server process
const serverPath = path.join(__dirname, '../../dist/index.js');
const server = spawn('node', [serverPath], {
stdio: ['pipe', 'pipe', 'pipe']
});
let responseBuffer = '';
let requestId = 1;
// Handle server output
server.stdout.on('data', (data) => {
responseBuffer += data.toString();
// Try to parse complete JSON-RPC messages
let lines = responseBuffer.split('\n');
responseBuffer = lines.pop() || ''; // Keep incomplete line
for (const line of lines) {
if (line.trim()) {
try {
const response = JSON.parse(line);
console.log('📨 Received:', JSON.stringify(response, null, 2));
} catch (e) {
console.log('📄 Raw output:', line);
}
}
}
});
server.stderr.on('data', (data) => {
console.log('🔍 Server stderr:', data.toString());
});
// Helper to send JSON-RPC request
function sendRequest(method, params = {}) {
const request = {
jsonrpc: '2.0',
method: method,
params: params,
id: requestId++
};
console.log('📤 Sending:', JSON.stringify(request, null, 2));
server.stdin.write(JSON.stringify(request) + '\n');
return new Promise(resolve => {
// Wait for response (simplified - in real implementation would match IDs)
const originalHandler = server.stdout.listeners('data')[0];
server.stdout.removeListener('data', originalHandler);
let buffer = '';
function handleResponse(data) {
buffer += data.toString();
let lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.trim()) {
try {
const response = JSON.parse(line);
if (response.id === request.id) {
server.stdout.removeListener('data', handleResponse);
server.stdout.addListener('data', originalHandler);
resolve(response);
return;
}
} catch (e) {
// Continue parsing
}
}
}
}
server.stdout.on('data', handleResponse);
// Timeout after 30 seconds for authentication calls
setTimeout(() => {
server.stdout.removeListener('data', handleResponse);
server.stdout.addListener('data', originalHandler);
resolve({ error: 'timeout' });
}, 30000);
});
}
try {
// Wait a moment for server to start
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('🔧 Step 1: Initialize MCP connection');
const initResponse = await sendRequest('initialize', {
protocolVersion: '1.0',
capabilities: {}
});
console.log('✅ Initialize response:', initResponse.result ? 'SUCCESS' : 'FAILED');
console.log('\n🔧 Step 2: List available tools');
const toolsResponse = await sendRequest('tools/list');
console.log('✅ Tools available:', toolsResponse.result?.tools?.length || 0);
// Find anomaly detection tool
const anomalyTool = toolsResponse.result?.tools?.find(t =>
t.name.includes('anomaly') || t.name.includes('api__anomaly_detection')
);
if (!anomalyTool) {
console.log('❌ Anomaly detection tool not found!');
console.log('Available tools:');
toolsResponse.result?.tools?.forEach(t => console.log(` - ${t.name}`));
return;
}
console.log(`\n🔧 Step 3: Test anomaly detection tool: ${anomalyTool.name}`);
console.log('📋 Tool description:', anomalyTool.description);
// Authenticate with correct credentials
console.log('\n🔐 Step 4: Authenticate user with correct credentials');
const authResponse = await sendRequest('tools/call', {
name: 'authenticate_user',
arguments: {
username: 'david+saola@umbrellacost.com',
password: 'Dsamsung1!'
}
});
console.log('✅ Auth response:', authResponse.result ? 'SUCCESS' : 'FAILED');
if (authResponse.error) {
console.log('❌ Auth error:', authResponse.error);
return;
}
if (authResponse.result?.content) {
console.log('📋 Auth details:', authResponse.result.content[0]?.text?.substring(0, 200) + '...');
}
console.log('\n🔧 Step 5: Call anomaly detection (simple test)');
const startTime = Date.now();
const anomalyResponse = await sendRequest('tools/call', {
name: anomalyTool.name,
arguments: {
startDate: '2025-08-01',
endDate: '2025-09-24',
isFull: 'false' // Start with false to test basic functionality
}
});
const duration = Date.now() - startTime;
console.log(`\n⏱️ Response time: ${duration}ms`);
if (anomalyResponse.result) {
console.log('✅ Anomaly detection SUCCESS!');
console.log('📊 Response type:', typeof anomalyResponse.result.content);
if (anomalyResponse.result.content && Array.isArray(anomalyResponse.result.content)) {
console.log('📄 Content items:', anomalyResponse.result.content.length);
if (anomalyResponse.result.content[0]) {
const firstItem = anomalyResponse.result.content[0];
if (firstItem.text) {
console.log('📝 Response preview:', firstItem.text.substring(0, 300) + '...');
}
}
}
} else if (anomalyResponse.error === 'timeout') {
console.log('⏰ Anomaly detection TIMED OUT after 30 seconds');
} else {
console.log('❌ Anomaly detection FAILED!');
console.log('Error:', anomalyResponse.error);
}
console.log('\n🔧 Step 6: Call anomaly detection with isFull=true (full test)');
const startTime2 = Date.now();
const anomalyFullResponse = await sendRequest('tools/call', {
name: anomalyTool.name,
arguments: {
startDate: '2025-08-01',
endDate: '2025-09-24',
isFull: 'true'
}
});
const duration2 = Date.now() - startTime2;
console.log(`\n⏱️ Full response time: ${duration2}ms`);
if (anomalyFullResponse.result) {
console.log('✅ Full anomaly detection SUCCESS!');
console.log('📊 Response type:', typeof anomalyFullResponse.result.content);
if (anomalyFullResponse.result.content && Array.isArray(anomalyFullResponse.result.content)) {
console.log('📄 Content items:', anomalyFullResponse.result.content.length);
if (anomalyFullResponse.result.content[0] && anomalyFullResponse.result.content[0].text) {
console.log('📝 Full response preview (first 500 chars):', anomalyFullResponse.result.content[0].text.substring(0, 500) + '...');
}
}
} else if (anomalyFullResponse.error === 'timeout') {
console.log('⏰ Full anomaly detection TIMED OUT after 30 seconds');
console.log('💡 This indicates a real timeout issue with large datasets');
} else {
console.log('❌ Full anomaly detection FAILED!');
console.log('Error:', anomalyFullResponse.error);
}
} catch (error) {
console.log('❌ Test failed:', error.message);
} finally {
server.kill();
}
}
testMCPStdioWithCorrectAuth().catch(console.error);