simple-mcp-client.js•4.36 kB
// Simple MCP Client using Node.js http module
import http from 'http';
class SimpleMCPClient {
constructor() {
this.sessionId = null;
this.requestId = 1;
this.hostname = 'localhost';
this.port = 5002;
this.path = '/mcp';
}
async request(method, params = {}) {
return new Promise((resolve, reject) => {
const postData = JSON.stringify({
jsonrpc: '2.0',
method: method,
params: params,
id: this.requestId++
});
const options = {
hostname: this.hostname,
port: this.port,
path: this.path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
'Content-Length': Buffer.byteLength(postData),
'Connection': 'keep-alive'
}
};
// Add session ID if available
if (this.sessionId) {
options.headers['mcp-session-id'] = this.sessionId;
}
console.log(`\n=== Request: ${method} ===`);
console.log('Headers:', options.headers);
console.log('Body:', postData);
const req = http.request(options, (res) => {
console.log(`\n=== Response: ${res.statusCode} ===`);
console.log('Headers:', res.headers);
// Save session ID from response headers (case-insensitive)
const sessionHeader = Object.entries(res.headers).find(
([key]) => key.toLowerCase() === 'mcp-session-id'
);
if (sessionHeader && sessionHeader[1]) {
this.sessionId = sessionHeader[1];
console.log('Session ID updated:', this.sessionId);
}
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Response body:', data);
try {
const result = data ? JSON.parse(data) : {};
if (res.statusCode >= 400) {
reject({
statusCode: res.statusCode,
headers: res.headers,
data: result
});
} else {
resolve({
statusCode: res.statusCode,
headers: res.headers,
data: result
});
}
} catch (error) {
reject({
statusCode: res.statusCode,
headers: res.headers,
error: error.message,
rawData: data
});
}
});
});
req.on('error', (error) => {
console.error('Request error:', error);
reject(error);
});
// Write data to request body
req.write(postData);
req.end();
});
}
async initialize() {
console.log('Initializing MCP client...');
const response = await this.request('initialize', {
protocolVersion: '1.0',
clientInfo: {
name: 'simple-mcp-client',
version: '1.0.0'
},
capabilities: {}
});
console.log('Initialization successful');
return response;
}
async listTools() {
return this.request('mcp.list_tools', {});
}
async ping() {
return this.request('spiderfoot_ping', {});
}
async listScans() {
return this.request('spiderfoot_scans', {});
}
}
// Test the client
async function testClient() {
const client = new SimpleMCPClient();
try {
// 1. Initialize the client
console.log('=== Testing Simple MCP Client ===');
await client.initialize();
if (!client.sessionId) {
throw new Error('Failed to get session ID');
}
// 2. List tools
console.log('\n=== Listing Tools ===');
const tools = await client.listTools();
console.log('Tools response:', JSON.stringify(tools, null, 2));
// 3. Test ping
console.log('\n=== Testing Ping ===');
const pingResult = await client.ping();
console.log('Ping result:', JSON.stringify(pingResult, null, 2));
// 4. List scans
console.log('\n=== Listing Scans ===');
const scans = await client.listScans();
console.log('Scans:', JSON.stringify(scans, null, 2));
console.log('\n✅ Test completed successfully!');
} catch (error) {
console.error('\n❌ Test failed:', error);
process.exit(1);
}
}
// Run the test
testClient();