test_server.py•4.12 kB
#!/usr/bin/env python3
"""
Simple test script for MCP server.
Sends test requests and validates responses.
"""
import subprocess
import json
import time
def send_request(process, request):
"""Send a JSON-RPC request to the server."""
request_line = json.dumps(request) + "\n"
process.stdin.write(request_line)
process.stdin.flush()
# Read response
response_line = process.stdout.readline()
return json.loads(response_line)
def test_server():
"""Run basic tests against the MCP server."""
print("Starting MCP server test...")
# Start the server
process = subprocess.Popen(
["python3", "server.py"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1
)
time.sleep(0.5) # Give server time to start
try:
# Test 1: Initialize
print("\n1. Testing initialize...")
init_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"clientInfo": {
"name": "test-client",
"version": "1.0"
}
}
}
response = send_request(process, init_request)
print(f" Response: {json.dumps(response, indent=2)}")
assert "result" in response
assert response["result"]["protocolVersion"] == "2024-11-05"
print(" ✓ Initialize successful")
# Test 2: List tools
print("\n2. Testing tools/list...")
list_request = {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}
response = send_request(process, list_request)
print(f" Response: {json.dumps(response, indent=2)}")
assert "result" in response
assert "tools" in response["result"]
tools = response["result"]["tools"]
tool_names = [t["name"] for t in tools]
assert "read_file" in tool_names
assert "write_file" in tool_names
print(f" ✓ Found {len(tools)} tools: {tool_names}")
# Test 3: Write file
print("\n3. Testing write_file...")
write_request = {
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "write_file",
"arguments": {
"path": "/tmp/mcp_test.txt",
"contents": "Hello from MCP server test!"
}
}
}
response = send_request(process, write_request)
print(f" Response: {json.dumps(response, indent=2)}")
assert "result" in response
print(" ✓ Write file successful")
# Test 4: Read file
print("\n4. Testing read_file...")
read_request = {
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "read_file",
"arguments": {
"path": "/tmp/mcp_test.txt"
}
}
}
response = send_request(process, read_request)
print(f" Response: {json.dumps(response, indent=2)}")
assert "result" in response
content = response["result"]["content"][0]["text"]
result_data = json.loads(content)
assert "Hello from MCP server test!" in result_data["content"]
print(" ✓ Read file successful")
print("\n✅ All tests passed!")
except Exception as e:
print(f"\n❌ Test failed: {e}")
# Print any stderr output
import select
if select.select([process.stderr], [], [], 0)[0]:
stderr = process.stderr.read()
print(f"\nServer stderr:\n{stderr}")
finally:
# Clean up
process.terminate()
process.wait(timeout=2)
print("\nServer stopped.")
if __name__ == "__main__":
test_server()