test-mcp-client.js•4.72 kB
// Test script for MCP client with SpiderFoot MCP server
import axios from 'axios';
const MCP_SERVER_URL = 'http://localhost:5002/mcp';
class MCPClient {
constructor() {
this.sessionId = null;
this.requestId = 1;
}
async initialize() {
try {
const response = await axios.post(
MCP_SERVER_URL,
{
jsonrpc: '2.0',
method: 'initialize',
params: {
protocolVersion: '1.0',
clientInfo: {
name: 'test-client',
version: '1.0.0'
},
capabilities: {}
},
id: this.requestId++
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
},
responseType: 'text'
}
);
// Parse SSE response
const sseData = this.parseSSEResponse(response.data);
// Extract session ID from headers
if (response.headers['mcp-session-id']) {
this.sessionId = response.headers['mcp-session-id'];
console.log('Session ID:', this.sessionId);
}
console.log('Initialization response:', sseData);
return sseData;
} catch (error) {
console.error('Initialization failed:', error.message);
if (error.response) {
console.error('Response status:', error.response.status);
console.error('Response headers:', error.response.headers);
console.error('Response data:', error.response.data);
}
throw error;
}
}
async callMethod(method, params = {}) {
if (!this.sessionId) {
throw new Error('Not initialized. Call initialize() first.');
}
try {
const response = await axios.post(
MCP_SERVER_URL,
{
jsonrpc: '2.0',
method: method,
params: params,
id: this.requestId++
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
'mcp-session-id': this.sessionId
},
responseType: 'text'
}
);
// Parse SSE response
const sseData = this.parseSSEResponse(response.data);
console.log(`Method ${method} response:`, sseData);
return sseData;
} catch (error) {
console.error(`Method ${method} call failed:`, error.message);
if (error.response) {
console.error('Response status:', error.response.status);
console.error('Response headers:', error.response.headers);
console.error('Response data:', error.response.data);
}
throw error;
}
}
parseSSEResponse(data) {
const lines = data.split('\n').filter(line => line.trim() !== '');
const result = {
event: null,
data: null,
id: null,
retry: null
};
for (const line of lines) {
const colonIndex = line.indexOf(':');
if (colonIndex === -1) continue;
const field = line.slice(0, colonIndex).trim();
let value = line.slice(colonIndex + 1).trim();
// Remove leading space if present
if (value.startsWith(' ')) {
value = value.slice(1);
}
if (field === 'data') {
try {
result.data = JSON.parse(value);
} catch (e) {
result.data = value;
}
} else if (field === 'event') {
result.event = value;
} else if (field === 'id') {
result.id = value;
} else if (field === 'retry') {
result.retry = parseInt(value, 10);
}
}
return result;
}
}
// Test the MCP client
async function testMCPClient() {
const client = new MCPClient();
try {
// 1. Initialize the client
console.log('1. Initializing MCP client...');
await client.initialize();
if (!client.sessionId) {
throw new Error('Failed to initialize MCP session');
}
// 2. List available tools
console.log('\n2. Listing available tools...');
const tools = await client.callMethod('tools/list');
// 3. If tools are available, try to call one
if (tools && tools.data && tools.data.result) {
const toolName = Object.keys(tools.data.result)[0];
if (toolName) {
console.log(`\n3. Calling tool: ${toolName}`);
const toolResult = await client.callMethod(toolName, {});
console.log('Tool result:', toolResult);
}
}
console.log('\n✅ MCP client test completed successfully!');
} catch (error) {
console.error('\n❌ MCP client test failed:', error.message);
process.exit(1);
}
}
// Run the test
testMCPClient();