Skip to content

Commit 6400bcd

Browse files
committed
fix: check port availability before starting HTTP server
1 parent fb027c1 commit 6400bcd

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/alertmanager_mcp_server/server.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/env python
22
import os
33
import logging
4+
import socket
45
import sys
56
from contextvars import ContextVar
67
from dataclasses import dataclass
@@ -38,6 +39,18 @@ def safe_print(text):
3839
print(text.encode('ascii', errors='replace').decode(), file=sys.stderr)
3940

4041

42+
def check_port(port):
43+
# Check port availability before starting HTTP server
44+
try:
45+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
46+
s.bind(('', port))
47+
except OSError as e:
48+
safe_print(f"Socket error: {e}")
49+
safe_print(
50+
f"Port {port} is already in use. Cannot start HTTP server.")
51+
sys.exit(1)
52+
53+
4154
dotenv.load_dotenv()
4255
mcp = FastMCP("Alertmanager MCP")
4356

@@ -756,13 +769,19 @@ def run_server():
756769

757770
# Launch the server with the selected transport mode
758771
if args.transport == 'sse':
772+
# Check port availability before starting HTTP server
773+
check_port(args.port)
774+
759775
safe_print("Running server with SSE transport (web-based)")
760776
# Run with SSE transport (web-based)
761777
# Create a Starlette app to serve the MCP server
762778
starlette_app = create_starlette_app(mcp_server, debug=True)
763779
# Start the web server with the configured host and port
764780
uvicorn.run(starlette_app, host=args.host, port=args.port)
765781
elif args.transport == 'http':
782+
# Check port availability before starting HTTP server
783+
check_port(args.port)
784+
766785
safe_print("Running server with http transport (streamable HTTP)")
767786
# Run with streamable-http transport served by uvicorn so host/port
768787
# CLI/env variables control the listening socket (same pattern as SSE).

0 commit comments

Comments
 (0)