Skip to content

Commit 7f37036

Browse files
committed
fix: improve MCP server readiness check in tests
Replace weak thread-alive check with actual port connectivity test to prevent connection refused errors in docker mode integration tests. Signed-off-by: Derek Higgins <derekh@redhat.com>
1 parent f30e486 commit 7f37036

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

tests/common/mcp.py

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -244,10 +244,8 @@ def run_server():
244244
logger.debug(f"Starting MCP server thread on port {port}")
245245
server_thread.start()
246246

247-
# Wait for the server thread to be running
248-
# Note: We can't use a simple HTTP GET health check on /sse because it's an SSE endpoint
249-
# that expects a long-lived connection, not a simple request/response
250-
timeout = 2
247+
# Wait for the server to be actually listening on the port
248+
timeout = 5
251249
start_time = time.time()
252250

253251
# Determine the appropriate host for the server URL based on test environment
@@ -257,18 +255,32 @@ def run_server():
257255

258256
mcp_host = os.environ.get("LLAMA_STACK_TEST_MCP_HOST", "localhost")
259257
server_url = f"http://{mcp_host}:{port}/sse"
260-
logger.debug(f"Waiting for MCP server thread to start on port {port} (accessible via {mcp_host})")
258+
logger.debug(f"Waiting for MCP server to listen on port {port} (accessible via {mcp_host})")
261259

260+
import socket
261+
262+
server_ready = False
262263
while time.time() - start_time < timeout:
263-
if server_thread.is_alive():
264-
# Give the server a moment to bind to the port
265-
time.sleep(0.1)
266-
logger.debug(f"MCP server is ready on port {port}")
264+
if not server_thread.is_alive():
265+
logger.error(f"MCP server thread died unexpectedly on port {port}")
267266
break
268-
time.sleep(0.05)
269-
else:
270-
# If we exit the loop due to timeout
271-
logger.error(f"MCP server thread failed to start within {timeout} seconds on port {port}")
267+
268+
# Check if port is actually listening
269+
try:
270+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
271+
sock.settimeout(0.1)
272+
result = sock.connect_ex(("127.0.0.1", port))
273+
if result == 0:
274+
logger.debug(f"MCP server is ready on port {port}")
275+
server_ready = True
276+
break
277+
except Exception as e:
278+
logger.debug(f"Port check failed: {e}")
279+
280+
time.sleep(0.1)
281+
282+
if not server_ready:
283+
logger.error(f"MCP server failed to become ready within {timeout} seconds on port {port}")
272284

273285
try:
274286
yield {"server_url": server_url}

0 commit comments

Comments
 (0)