test-mcp.js•7.85 kB
#!/usr/bin/env node
/**
* Test script for Aptos MCP Server
* This script tests the MCP server by sending various requests and checking responses
*/
import { spawn } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log('🧪 Testing Aptos MCP Server...\n');
// Test configuration
const TEST_PRIVATE_KEY = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
const TEST_ACCOUNT = '0x1'; // Well-known test account
const TIMEOUT = 5000; // 5 seconds timeout for each test
class MCPTester {
constructor() {
this.server = null;
this.requestId = 1;
this.responses = new Map();
}
async startServer() {
console.log('🚀 Starting MCP server...');
const env = {
...process.env,
APTOS_MCP_PRIVATE_KEY: TEST_PRIVATE_KEY,
APTOS_MCP_NETWORK: 'testnet'
};
const serverPath = join(__dirname, 'build', 'index.js');
this.server = spawn('node', [serverPath], {
env,
stdio: ['pipe', 'pipe', 'pipe']
});
this.server.stdout.on('data', (data) => {
const lines = data.toString().split('\n').filter(line => line.trim());
for (const line of lines) {
try {
const response = JSON.parse(line);
if (response.id) {
this.responses.set(response.id, response);
}
} catch (e) {
// Ignore non-JSON lines
}
}
});
this.server.stderr.on('data', (data) => {
const output = data.toString();
if (output.includes('Aptos Blockchain MCP Server running on stdio')) {
console.log('✅ Server started successfully\n');
}
});
// Wait for server to start
await new Promise(resolve => setTimeout(resolve, 1000));
}
async sendRequest(method, params = {}) {
const id = this.requestId++;
const request = {
jsonrpc: '2.0',
id,
method,
params
};
console.log(`📤 Sending: ${method}`);
this.server.stdin.write(JSON.stringify(request) + '\n');
// Wait for response
const startTime = Date.now();
while (Date.now() - startTime < TIMEOUT) {
if (this.responses.has(id)) {
const response = this.responses.get(id);
this.responses.delete(id);
return response;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
throw new Error(`Timeout waiting for response to ${method}`);
}
async testListTools() {
console.log('🔧 Testing: List Tools');
try {
const response = await this.sendRequest('tools/list');
if (response.result && response.result.tools) {
console.log(`✅ Found ${response.result.tools.length} tools:`);
response.result.tools.forEach(tool => {
console.log(` - ${tool.name}: ${tool.description.substring(0, 60)}...`);
});
return true;
} else {
console.log('❌ Invalid tools list response');
return false;
}
} catch (error) {
console.log(`❌ Error: ${error.message}`);
return false;
}
}
async testCreateAccount() {
console.log('\n👤 Testing: Create Account');
try {
const response = await this.sendRequest('tools/call', {
name: 'create_account',
arguments: {}
});
if (response.result && !response.result.isError) {
console.log('✅ Account created successfully');
console.log('📄 Response preview:', response.result.content[0].text.substring(0, 100) + '...');
return true;
} else {
console.log('❌ Failed to create account');
if (response.result?.content) {
console.log('Error:', response.result.content[0].text);
}
return false;
}
} catch (error) {
console.log(`❌ Error: ${error.message}`);
return false;
}
}
async testGetBalance() {
console.log('\n💰 Testing: Get APT Balance');
try {
const response = await this.sendRequest('tools/call', {
name: 'get_apt_balance',
arguments: {
account_address: TEST_ACCOUNT
}
});
if (response.result) {
if (response.result.isError) {
console.log('⚠️ Expected error for test account (account may not exist)');
console.log('📄 Response:', response.result.content[0].text.substring(0, 150));
} else {
console.log('✅ Balance retrieved successfully');
console.log('📄 Response:', response.result.content[0].text);
}
return true;
} else {
console.log('❌ Invalid balance response');
return false;
}
} catch (error) {
console.log(`❌ Error: ${error.message}`);
return false;
}
}
async testGetAccountInfo() {
console.log('\n📋 Testing: Get Account Info');
try {
const response = await this.sendRequest('tools/call', {
name: 'get_account_info',
arguments: {
account_address: TEST_ACCOUNT
}
});
if (response.result) {
if (response.result.isError) {
console.log('⚠️ Expected error for test account (account may not exist)');
console.log('📄 Response:', response.result.content[0].text.substring(0, 150));
} else {
console.log('✅ Account info retrieved successfully');
console.log('📄 Response:', response.result.content[0].text);
}
return true;
} else {
console.log('❌ Invalid account info response');
return false;
}
} catch (error) {
console.log(`❌ Error: ${error.message}`);
return false;
}
}
async testInvalidTool() {
console.log('\n❓ Testing: Invalid Tool Call');
try {
const response = await this.sendRequest('tools/call', {
name: 'nonexistent_tool',
arguments: {}
});
if (response.result && response.result.isError) {
console.log('✅ Properly handled invalid tool call');
console.log('📄 Error message:', response.result.content[0].text);
return true;
} else {
console.log('❌ Should have returned error for invalid tool');
return false;
}
} catch (error) {
console.log(`❌ Error: ${error.message}`);
return false;
}
}
async runAllTests() {
const tests = [
{ name: 'List Tools', fn: () => this.testListTools() },
{ name: 'Create Account', fn: () => this.testCreateAccount() },
{ name: 'Get Balance', fn: () => this.testGetBalance() },
{ name: 'Get Account Info', fn: () => this.testGetAccountInfo() },
{ name: 'Invalid Tool', fn: () => this.testInvalidTool() }
];
let passed = 0;
let total = tests.length;
for (const test of tests) {
try {
const result = await test.fn();
if (result) passed++;
} catch (error) {
console.log(`❌ Test "${test.name}" failed with error:`, error.message);
}
}
console.log(`\n📊 Test Results: ${passed}/${total} tests passed`);
if (passed === total) {
console.log('🎉 All tests passed! Your Aptos MCP server is working correctly.');
} else {
console.log('⚠️ Some tests failed. Check the output above for details.');
}
return passed === total;
}
cleanup() {
if (this.server) {
this.server.kill();
}
}
}
// Run the tests
async function main() {
const tester = new MCPTester();
try {
await tester.startServer();
await tester.runAllTests();
} catch (error) {
console.error('💥 Test suite failed:', error.message);
} finally {
tester.cleanup();
process.exit(0);
}
}
main().catch(console.error);