|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Generate both TCP and WebSocket MCP traffic for testing MCPHawk.""" |
| 3 | + |
| 4 | +import asyncio |
| 5 | +import contextlib |
| 6 | +import json |
| 7 | +import logging |
| 8 | +import socket |
| 9 | +import subprocess |
| 10 | +import sys |
| 11 | +import time |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | +import websockets |
| 15 | + |
| 16 | +logging.basicConfig( |
| 17 | + level=logging.INFO, |
| 18 | + format='%(asctime)s [%(levelname)s] %(message)s' |
| 19 | +) |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +def run_tcp_server(): |
| 24 | + """Run the TCP server in a subprocess.""" |
| 25 | + script_path = Path(__file__).parent / "tcp_server.py" |
| 26 | + return subprocess.Popen([sys.executable, str(script_path)]) |
| 27 | + |
| 28 | + |
| 29 | +def run_ws_server(): |
| 30 | + """Run the WebSocket server in a subprocess.""" |
| 31 | + script_path = Path(__file__).parent / "ws_server.py" |
| 32 | + return subprocess.Popen([sys.executable, str(script_path)]) |
| 33 | + |
| 34 | + |
| 35 | +def send_tcp_traffic(): |
| 36 | + """Send TCP MCP traffic.""" |
| 37 | + logger.info("Sending TCP traffic...") |
| 38 | + |
| 39 | + try: |
| 40 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 41 | + sock.connect(('localhost', 12345)) |
| 42 | + |
| 43 | + messages = [ |
| 44 | + {"jsonrpc": "2.0", "method": "initialize", "params": {"protocolVersion": "2024-11-05"}, "id": 1}, |
| 45 | + {"jsonrpc": "2.0", "method": "tools/list", "id": 2}, |
| 46 | + {"jsonrpc": "2.0", "method": "notifications/tcp_test", "params": {"source": "tcp"}}, |
| 47 | + {"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "test_tool", "arguments": {}}, "id": 3}, |
| 48 | + ] |
| 49 | + |
| 50 | + for msg in messages: |
| 51 | + data = json.dumps(msg).encode('utf-8') |
| 52 | + sock.sendall(data) |
| 53 | + logger.info(f" TCP sent: {msg.get('method')}") |
| 54 | + |
| 55 | + # Read response if it has an ID |
| 56 | + if "id" in msg: |
| 57 | + try: |
| 58 | + response = sock.recv(1024) |
| 59 | + if response: |
| 60 | + logger.info(" TCP received response") |
| 61 | + except Exception: |
| 62 | + pass |
| 63 | + |
| 64 | + time.sleep(0.2) |
| 65 | + |
| 66 | + # Keep connection open a bit longer |
| 67 | + time.sleep(1) |
| 68 | + sock.close() |
| 69 | + |
| 70 | + except Exception as e: |
| 71 | + logger.error(f"TCP client error: {e}") |
| 72 | + |
| 73 | + |
| 74 | +async def send_ws_traffic(): |
| 75 | + """Send WebSocket MCP traffic.""" |
| 76 | + logger.info("Sending WebSocket traffic...") |
| 77 | + |
| 78 | + try: |
| 79 | + async with websockets.connect("ws://localhost:8765", compression=None) as ws: |
| 80 | + messages = [ |
| 81 | + {"jsonrpc": "2.0", "method": "initialize", "params": {"protocolVersion": "2024-11-05"}, "id": 1}, |
| 82 | + {"jsonrpc": "2.0", "method": "tools/list", "id": 2}, |
| 83 | + {"jsonrpc": "2.0", "method": "notifications/ws_test", "params": {"source": "websocket"}}, |
| 84 | + {"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "calculator", "arguments": {"a": 10, "b": 20}}, "id": 3}, |
| 85 | + ] |
| 86 | + |
| 87 | + for msg in messages: |
| 88 | + await ws.send(json.dumps(msg)) |
| 89 | + logger.info(f" WS sent: {msg.get('method')}") |
| 90 | + |
| 91 | + # Wait for response if it has an ID |
| 92 | + if "id" in msg: |
| 93 | + await ws.recv() |
| 94 | + logger.info(" WS received response") |
| 95 | + else: |
| 96 | + await asyncio.sleep(0.2) |
| 97 | + |
| 98 | + except Exception as e: |
| 99 | + logger.error(f"WebSocket client error: {e}") |
| 100 | + |
| 101 | + |
| 102 | +def check_port(port): |
| 103 | + """Check if a port is available.""" |
| 104 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 105 | + result = sock.connect_ex(('localhost', port)) |
| 106 | + sock.close() |
| 107 | + return result != 0 |
| 108 | + |
| 109 | + |
| 110 | +async def main(): |
| 111 | + """Generate all traffic types.""" |
| 112 | + logger.info("MCPHawk Traffic Generator") |
| 113 | + logger.info("========================\n") |
| 114 | + |
| 115 | + # Check if ports are available |
| 116 | + if not check_port(12345): |
| 117 | + logger.error("Port 12345 is already in use. Please stop the existing TCP server.") |
| 118 | + return |
| 119 | + |
| 120 | + if not check_port(8765): |
| 121 | + logger.error("Port 8765 is already in use. Please stop the existing WebSocket server.") |
| 122 | + return |
| 123 | + |
| 124 | + logger.info("Starting servers...") |
| 125 | + |
| 126 | + # Start servers |
| 127 | + tcp_server = run_tcp_server() |
| 128 | + ws_server = run_ws_server() |
| 129 | + |
| 130 | + # Give servers time to start |
| 131 | + logger.info("Waiting for servers to start...") |
| 132 | + await asyncio.sleep(2) |
| 133 | + |
| 134 | + try: |
| 135 | + # Send TCP traffic |
| 136 | + send_tcp_traffic() |
| 137 | + |
| 138 | + # Send WebSocket traffic |
| 139 | + await send_ws_traffic() |
| 140 | + |
| 141 | + logger.info("\n✅ All traffic sent successfully!") |
| 142 | + logger.info("\nServers will continue running. Press Ctrl+C to stop.") |
| 143 | + |
| 144 | + # Keep running |
| 145 | + await asyncio.Future() |
| 146 | + |
| 147 | + except KeyboardInterrupt: |
| 148 | + logger.info("\nStopping servers...") |
| 149 | + finally: |
| 150 | + # Clean up |
| 151 | + tcp_server.terminate() |
| 152 | + ws_server.terminate() |
| 153 | + tcp_server.wait() |
| 154 | + ws_server.wait() |
| 155 | + logger.info("Servers stopped.") |
| 156 | + |
| 157 | + |
| 158 | +if __name__ == "__main__": |
| 159 | + with contextlib.suppress(KeyboardInterrupt): |
| 160 | + asyncio.run(main()) |
| 161 | + |
0 commit comments