|
| 1 | +""" |
| 2 | +Router command for managing the MCPRouter daemon process |
| 3 | +""" |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import signal |
| 8 | +import subprocess |
| 9 | +import sys |
| 10 | + |
| 11 | +import click |
| 12 | +import psutil |
| 13 | +from rich.console import Console |
| 14 | + |
| 15 | +from mcpm.utils.platform import get_log_directory, get_pid_directory |
| 16 | + |
| 17 | +logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | +console = Console() |
| 20 | + |
| 21 | +APP_SUPPORT_DIR = get_pid_directory("mcpm") |
| 22 | +APP_SUPPORT_DIR.mkdir(parents=True, exist_ok=True) |
| 23 | +PID_FILE = APP_SUPPORT_DIR / "router.pid" |
| 24 | + |
| 25 | +LOG_DIR = get_log_directory("mcpm") |
| 26 | +LOG_DIR.mkdir(parents=True, exist_ok=True) |
| 27 | + |
| 28 | + |
| 29 | +def is_process_running(pid): |
| 30 | + """check if the process is running""" |
| 31 | + try: |
| 32 | + return psutil.pid_exists(pid) |
| 33 | + except Exception: |
| 34 | + return False |
| 35 | + |
| 36 | + |
| 37 | +def read_pid_file(): |
| 38 | + """read the pid file and return the process id, if the file does not exist or the process is not running, return None""" |
| 39 | + if not PID_FILE.exists(): |
| 40 | + return None |
| 41 | + |
| 42 | + try: |
| 43 | + pid = int(PID_FILE.read_text().strip()) |
| 44 | + if is_process_running(pid): |
| 45 | + return pid |
| 46 | + else: |
| 47 | + # if the process is not running, delete the pid file |
| 48 | + remove_pid_file() |
| 49 | + return None |
| 50 | + except (ValueError, IOError) as e: |
| 51 | + logger.error(f"Error reading PID file: {e}") |
| 52 | + return None |
| 53 | + |
| 54 | + |
| 55 | +def write_pid_file(pid): |
| 56 | + """write the process id to the pid file""" |
| 57 | + try: |
| 58 | + PID_FILE.write_text(str(pid)) |
| 59 | + logger.info(f"PID {pid} written to {PID_FILE}") |
| 60 | + except IOError as e: |
| 61 | + logger.error(f"Error writing PID file: {e}") |
| 62 | + sys.exit(1) |
| 63 | + |
| 64 | + |
| 65 | +def remove_pid_file(): |
| 66 | + """remove the pid file""" |
| 67 | + try: |
| 68 | + PID_FILE.unlink(missing_ok=True) |
| 69 | + except IOError as e: |
| 70 | + logger.error(f"Error removing PID file: {e}") |
| 71 | + |
| 72 | + |
| 73 | +@click.group(name="router") |
| 74 | +def router(): |
| 75 | + """Manage MCP router service.""" |
| 76 | + pass |
| 77 | + |
| 78 | + |
| 79 | +@router.command(name="on") |
| 80 | +@click.option("--host", type=str, default="0.0.0.0", help="Host to bind the SSE server to") |
| 81 | +@click.option("--port", type=int, default=8080, help="Port to bind the SSE server to") |
| 82 | +@click.option("--cors", type=str, help="Comma-separated list of allowed origins for CORS") |
| 83 | +def start_router(host, port, cors): |
| 84 | + """Start MCPRouter as a daemon process. |
| 85 | +
|
| 86 | + Example: |
| 87 | + mcpm router on |
| 88 | + mcpm router on --port 8888 |
| 89 | + mcpm router on --host 0.0.0.0 --port 9000 |
| 90 | + """ |
| 91 | + # check if there is a router already running |
| 92 | + existing_pid = read_pid_file() |
| 93 | + if existing_pid: |
| 94 | + console.print(f"[bold red]Error:[/] MCPRouter is already running (PID: {existing_pid})") |
| 95 | + console.print("Use 'mcpm router off' to stop the running instance.") |
| 96 | + return |
| 97 | + |
| 98 | + # prepare environment variables |
| 99 | + env = os.environ.copy() |
| 100 | + if cors: |
| 101 | + env["MCPM_ROUTER_CORS"] = cors |
| 102 | + |
| 103 | + # prepare uvicorn command |
| 104 | + uvicorn_cmd = [ |
| 105 | + sys.executable, |
| 106 | + "-m", |
| 107 | + "uvicorn", |
| 108 | + "mcpm.router.app:app", |
| 109 | + "--host", |
| 110 | + host, |
| 111 | + "--port", |
| 112 | + str(port), |
| 113 | + "--timeout-graceful-shutdown", |
| 114 | + "5", |
| 115 | + ] |
| 116 | + |
| 117 | + # start process |
| 118 | + try: |
| 119 | + # create log file |
| 120 | + log_file = LOG_DIR / "router_access.log" |
| 121 | + |
| 122 | + # open log file, prepare to redirect stdout and stderr |
| 123 | + with open(log_file, "a") as log: |
| 124 | + # use subprocess.Popen to start uvicorn |
| 125 | + process = subprocess.Popen( |
| 126 | + uvicorn_cmd, |
| 127 | + stdout=log, |
| 128 | + stderr=log, |
| 129 | + env=env, |
| 130 | + start_new_session=True, # create new session, so the process won't be affected by terminal closing |
| 131 | + ) |
| 132 | + |
| 133 | + # record PID |
| 134 | + pid = process.pid |
| 135 | + write_pid_file(pid) |
| 136 | + |
| 137 | + console.print(f"[bold green]MCPRouter started[/] at http://{host}:{port} (PID: {pid})") |
| 138 | + console.print(f"Log file: {log_file}") |
| 139 | + console.print("Use 'mcpm router off' to stop the router.") |
| 140 | + |
| 141 | + except Exception as e: |
| 142 | + console.print(f"[bold red]Error:[/] Failed to start MCPRouter: {e}") |
| 143 | + |
| 144 | + |
| 145 | +@router.command(name="off") |
| 146 | +def stop_router(): |
| 147 | + """Stop the running MCPRouter daemon process. |
| 148 | +
|
| 149 | + Example: |
| 150 | + mcpm router off |
| 151 | + """ |
| 152 | + # check if there is a router already running |
| 153 | + pid = read_pid_file() |
| 154 | + if not pid: |
| 155 | + console.print("[yellow]MCPRouter is not running.[/]") |
| 156 | + return |
| 157 | + |
| 158 | + # send termination signal |
| 159 | + try: |
| 160 | + os.kill(pid, signal.SIGTERM) |
| 161 | + console.print(f"[bold green]MCPRouter stopped (PID: {pid})[/]") |
| 162 | + |
| 163 | + # delete PID file |
| 164 | + remove_pid_file() |
| 165 | + except OSError as e: |
| 166 | + console.print(f"[bold red]Error:[/] Failed to stop MCPRouter: {e}") |
| 167 | + |
| 168 | + # if process does not exist, clean up PID file |
| 169 | + if e.errno == 3: # "No such process" |
| 170 | + console.print("[yellow]Process does not exist, cleaning up PID file...[/]") |
| 171 | + remove_pid_file() |
| 172 | + |
| 173 | + |
| 174 | +@router.command(name="status") |
| 175 | +def router_status(): |
| 176 | + """Check the status of the MCPRouter daemon process. |
| 177 | +
|
| 178 | + Example: |
| 179 | + mcpm router status |
| 180 | + """ |
| 181 | + pid = read_pid_file() |
| 182 | + if pid: |
| 183 | + console.print(f"[bold green]MCPRouter is running[/] (PID: {pid})") |
| 184 | + else: |
| 185 | + console.print("[yellow]MCPRouter is not running.[/]") |
0 commit comments