Skip to content

Commit 89bf558

Browse files
authored
fix: add port availability check and improve status message for MCPRouter (#124)
1 parent 99bb8dd commit 89bf558

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/mcpm/commands/router.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import os
77
import secrets
88
import signal
9+
import socket
910
import subprocess
1011
import sys
1112
import uuid
@@ -40,6 +41,35 @@ def is_process_running(pid):
4041
except Exception:
4142
return False
4243

44+
def is_port_listening(host, port) -> bool:
45+
"""
46+
Check if the specified (host, port) is being listened on.
47+
48+
Args:
49+
host: The host to check
50+
port: The port to check
51+
52+
Returns:
53+
True if the (host, port) is being listened on
54+
"""
55+
sock = None
56+
try:
57+
# Try to connect to the port
58+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
59+
sock.settimeout(1)
60+
connected_host = "127.0.0.1" if host == "0.0.0.0" else host
61+
result = sock.connect_ex((connected_host, port))
62+
# result == 0 means connection successful, which means port is in use
63+
# result != 0 means connection failed, which means port is not in use
64+
# result == 61 means ECONNREFUSED
65+
return result == 0
66+
except Exception as e:
67+
logger.error(f"Error checking host {host} and port {port}: {e}")
68+
return False
69+
finally:
70+
if sock:
71+
sock.close()
72+
4373

4474
def read_pid_file():
4575
"""read the pid file and return the process id, if the file does not exist or the process is not running, return None"""
@@ -285,6 +315,15 @@ def router_status():
285315
# check process status
286316
pid = read_pid_file()
287317
if pid:
318+
if not is_port_listening(host, port):
319+
console.print(
320+
f"[bold yellow]Notice:[/] [bold cyan]{host}:{port}[/] is not yet accepting connections. The service may still be starting up. Please wait a few seconds and try again."
321+
)
322+
console.print(
323+
f"[yellow]If this message persists after waiting, please check the log for more details.[/] (Log file: {LOG_DIR / 'router_access.log'})"
324+
)
325+
return
326+
288327
console.print(f"[bold green]MCPRouter is running[/] at http://{host}:{port} (PID: {pid})")
289328
share_config = ConfigManager().read_share_config()
290329
if share_config.get("pid"):

0 commit comments

Comments
 (0)