BluestoneApps MCP Remote Server

#!/usr/bin/env python3 """ MCP Remote Proxy - Forwards MCP requests to a remote server """ import json import sys import base64 import urllib.request import urllib.error import logging import threading # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename='/tmp/mcp_proxy.log', filemode='a' ) logger = logging.getLogger("mcp_remote_proxy") # Remote server configuration REMOTE_URL = "http://107.191.37.244:5051/jsonrpc" USERNAME = "admin" PASSWORD = "n2hXUijptRwpe9v6wZ37yOgEx4P8w3ofDRO0ko4A" AUTH_HEADER = f"Basic {base64.b64encode(f'{USERNAME}:{PASSWORD}'.encode()).decode()}" def forward_request(request_data): """Forward a request to the remote server.""" headers = { "Content-Type": "application/json", "Authorization": AUTH_HEADER } try: # Prepare the request data = json.dumps(request_data).encode('utf-8') req = urllib.request.Request(REMOTE_URL, data=data, headers=headers, method="POST") # Send the request with urllib.request.urlopen(req) as response: response_data = json.loads(response.read().decode('utf-8')) return response_data except urllib.error.HTTPError as e: logger.error(f"HTTP Error: {e.code} {e.reason}") return {"jsonrpc": "2.0", "error": {"code": -32000, "message": f"Remote server error: {e.code} {e.reason}"}, "id": request_data.get("id")} except Exception as e: logger.error(f"Exception when forwarding request: {e}") return {"jsonrpc": "2.0", "error": {"code": -32000, "message": f"Proxy error: {str(e)}"}, "id": request_data.get("id")} def main(): """Main function.""" logger.info("Starting MCP Remote Proxy") logger.info(f"Remote URL: {REMOTE_URL}") # Test connection test_request = {"jsonrpc": "2.0", "method": "tools/list", "id": 0} test_response = forward_request(test_request) if "error" in test_response: logger.error(f"Failed to connect to remote server: {test_response['error']}") sys.stdout.write(json.dumps(test_response) + "\n") sys.stdout.flush() else: logger.info("Successfully connected to remote server") # Process requests while True: try: # Read request from stdin line = sys.stdin.readline() if not line: break # Parse request request_data = json.loads(line) logger.info(f"Received request: {request_data.get('method')}") # Forward request to remote server response_data = forward_request(request_data) # Write response to stdout sys.stdout.write(json.dumps(response_data) + "\n") sys.stdout.flush() logger.info(f"Sent response for: {request_data.get('method')}") except json.JSONDecodeError as e: logger.error(f"Invalid JSON: {line} - {e}") sys.stdout.write(json.dumps({ "jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": None }) + "\n") sys.stdout.flush() except Exception as e: logger.error(f"Unexpected error: {e}") sys.stdout.write(json.dumps({ "jsonrpc": "2.0", "error": {"code": -32000, "message": f"Proxy error: {str(e)}"}, "id": None }) + "\n") sys.stdout.flush() if __name__ == "__main__": main()