const { spawn } = require('child_process');
const path = require('path');
const SERVER_PATH = path.join(__dirname, 'build', 'index.js');
const LIST_TOOLS_REQUEST = {
jsonrpc: '2.0',
id: 1,
method: 'listTools',
params: {}
};
const SEARCH_CODE_REQUEST = {
jsonrpc: '2.0',
id: 2,
method: 'callTool',
params: {
name: 'search_code',
arguments: {
path: process.cwd(),
query: 'search',
maxResults: 5
}
}
};
function sendRequest(server, request) {
const content = JSON.stringify(request);
const message = `Content-Length: ${Buffer.byteLength(content, 'utf8')}\r\n\r\n${content}`;
server.stdin.write(message);
}
console.log('Starting MCP server test...');
const server = spawn('node', [SERVER_PATH], {
stdio: ['pipe', 'pipe', 'pipe']
});
let responseBuffer = '';
let contentLength = null;
server.stdout.on('data', (data) => {
const chunk = data.toString();
responseBuffer += chunk;
while (responseBuffer.length > 0) {
if (contentLength === null) {
const headerMatch = responseBuffer.match(/Content-Length: (\d+)\r\n\r\n/);
if (headerMatch) {
contentLength = parseInt(headerMatch[1], 10);
responseBuffer = responseBuffer.substring(headerMatch[0].length);
} else {
break;
}
}
if (contentLength !== null && responseBuffer.length >= contentLength) {
const content = responseBuffer.substring(0, contentLength);
responseBuffer = responseBuffer.substring(contentLength);
contentLength = null;
try {
const response = JSON.parse(content);
console.log('Received response:', JSON.stringify(response, null, 2));
} catch (error) {
console.error('Error parsing response:', error);
}
} else {
break;
}
}
});
server.stderr.on('data', (data) => {
console.error(`stderr: ${data.toString()}`);
});
const timeout = setTimeout(() => {
console.log('Test timed out after 10 seconds');
server.kill();
process.exit(1);
}, 10000);
server.on('close', (code) => {
console.log(`Server process exited with code ${code}`);
});
setTimeout(() => {
console.log('1. Testing listTools request...');
sendRequest(server, LIST_TOOLS_REQUEST);
setTimeout(() => {
console.log('2. Testing callTool request for search_code...');
sendRequest(server, SEARCH_CODE_REQUEST);
setTimeout(() => {
console.log('Test completed.');
server.kill();
}, 5000);
}, 2000);
}, 1000);