mcp-client.mjs•2.27 kB
import axios from 'axios';
class MCPClient {
constructor(baseUrl = 'http://localhost:5002') {
this.baseUrl = baseUrl;
this.sessionId = null;
this.requestId = 1;
}
async initialize() {
const response = await this._request('mcp.initialize', {});
this.sessionId = response.headers['mcp-session-id'];
return response.data;
}
async listTools() {
return this._request('mcp.list_tools', {});
}
async callTool(toolName, params = {}) {
return this._request('mcp.call_tool', {
name: toolName,
parameters: params
});
}
async _request(method, params) {
const headers = {
'Content-Type': 'application/json',
};
if (this.sessionId) {
headers['mcp-session-id'] = this.sessionId;
}
try {
const response = await axios({
method: 'post',
url: `${this.baseUrl}/mcp`,
headers,
data: {
jsonrpc: '2.0',
id: this.requestId++,
method,
params
}
});
return response;
} catch (error) {
console.error('MCP Request failed:', error.message);
if (error.response) {
console.error('Response data:', error.response.data);
console.error('Response status:', error.response.status);
console.error('Response headers:', error.response.headers);
}
throw error;
}
}
}
// Example usage
async function main() {
const client = new MCPClient();
try {
// Initialize session
console.log('Initializing MCP session...');
await client.initialize();
console.log('Session ID:', client.sessionId);
// List available tools
console.log('\nListing available tools...');
const tools = await client.listTools();
console.log('Available tools:', JSON.stringify(tools.data, null, 2));
// Example: Call ping tool
console.log('\nPinging SpiderFoot...');
const pingResult = await client.callTool('spiderfoot_ping');
console.log('Ping result:', JSON.stringify(pingResult.data, null, 2));
} catch (error) {
console.error('Error:', error.message);
process.exit(1);
}
}
// Only run if executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
main();
}
export default MCPClient;