test-client.js•4.06 kB
#!/usr/bin/env node
/**
* MCP Server Test Client
*
* This file demonstrates how to interact with an MCP server programmatically.
* It shows examples of calling tools, reading resources, and using prompts.
*/
import { spawn } from 'child_process';
class MCPTestClient {
constructor() {
this.messageId = 1;
}
/**
* Send a JSON-RPC message to the MCP server and get response
*/
async sendMessage(server, message) {
return new Promise((resolve, reject) => {
let response = '';
const timeout = setTimeout(() => {
reject(new Error('Request timeout'));
}, 5000);
server.stdout.on('data', (data) => {
response += data.toString();
try {
const jsonResponse = JSON.parse(response.trim());
clearTimeout(timeout);
resolve(jsonResponse);
} catch (e) {
// Partial JSON, continue reading
}
});
server.stdin.write(JSON.stringify(message) + '\n');
});
}
/**
* Test the MCP server by calling various methods
*/
async testServer() {
console.log('🚀 Starting MCP Server Test Client\n');
// Start the MCP server
const server = spawn('node', ['server.js'], {
stdio: ['pipe', 'pipe', 'inherit']
});
try {
// Initialize the connection
console.log('📡 Initializing connection...');
const initResponse = await this.sendMessage(server, {
jsonrpc: '2.0',
id: this.messageId++,
method: 'initialize',
params: {
protocolVersion: '2024-11-05',
capabilities: {
roots: {
listChanged: true
},
sampling: {}
},
clientInfo: {
name: 'test-client',
version: '1.0.0'
}
}
});
console.log('✅ Initialized successfully');
// Test listing tools
console.log('\n🔧 Testing Tools...');
const toolsResponse = await this.sendMessage(server, {
jsonrpc: '2.0',
id: this.messageId++,
method: 'tools/list'
});
console.log('Available tools:', toolsResponse.result.tools.map(t => t.name).join(', '));
// Test calling a tool
console.log('\n🧮 Testing calculate tool...');
const calcResponse = await this.sendMessage(server, {
jsonrpc: '2.0',
id: this.messageId++,
method: 'tools/call',
params: {
name: 'calculate',
arguments: {
expression: '5 * 8 + 12'
}
}
});
console.log('Calculation result:', calcResponse.result.content[0].text);
// Test listing resources
console.log('\n📚 Testing Resources...');
const resourcesResponse = await this.sendMessage(server, {
jsonrpc: '2.0',
id: this.messageId++,
method: 'resources/list'
});
console.log('Available resources:', resourcesResponse.result.resources.map(r => r.name).join(', '));
// Test reading a resource
console.log('\n📖 Testing resource reading...');
const resourceResponse = await this.sendMessage(server, {
jsonrpc: '2.0',
id: this.messageId++,
method: 'resources/read',
params: {
uri: 'file://system-status'
}
});
console.log('System status preview:', resourceResponse.result.contents[0].text.split('\n').slice(0, 5).join('\n'));
// Test listing prompts
console.log('\n📝 Testing Prompts...');
const promptsResponse = await this.sendMessage(server, {
jsonrpc: '2.0',
id: this.messageId++,
method: 'prompts/list'
});
console.log('Available prompts:', promptsResponse.result.prompts.map(p => p.name).join(', '));
console.log('\n✅ All tests completed successfully!');
} catch (error) {
console.error('❌ Test failed:', error.message);
} finally {
server.kill();
}
}
}
// Run the tests
const client = new MCPTestClient();
client.testServer().catch(console.error);