Skip to content

Commit e460401

Browse files
committed
fix: add port availability check and improve status message for MCPRouter
1 parent 88c0182 commit e460401

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"""
@@ -270,6 +300,15 @@ def router_status():
270300
# check process status
271301
pid = read_pid_file()
272302
if pid:
303+
if not is_port_listening(host, port):
304+
console.print(
305+
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."
306+
)
307+
console.print(
308+
f"[yellow]If this message persists after waiting, please check the log for more details.[/] (Log file: {LOG_DIR / 'router_access.log'})"
309+
)
310+
return
311+
273312
console.print(f"[bold green]MCPRouter is running[/] at http://{host}:{port} (PID: {pid})")
274313
share_config = ConfigManager().read_share_config()
275314
if share_config.get("pid"):

0 commit comments

Comments
 (0)