Fix MCP connection refused error
connection refused error in MCP usually means the client cannot reach the MCP server due to incorrect transport setup or the server not running. Ensure you start the MCP server (e.g., stdio_server) before connecting and use the correct transport method (stdio or SSE) without TCP ports like 25565.config_error Why this happens
The connection refused error occurs when the MCP client tries to connect to a server that is not running or is unreachable. A common mistake is attempting to connect via a TCP port (like 25565) which is used by Minecraft servers, not MCP. MCP servers use stdio or SSE transports, and the server must be started before the client connects.
Example of incorrect client code that triggers this error:
from mcp.server.stdio import stdio_server
# This code is incomplete or missing server start
# Trying to connect to TCP port 25565 (Minecraft port) instead of stdio
# No server running, so connection refused error occurs
# Incorrect: no server running, client tries TCP connection (not supported) ConnectionRefusedError: [Errno 111] Connection refused
The fix
Start the MCP server using the stdio_server or appropriate server method before the client connects. Use the stdio transport which communicates over standard input/output streams, not TCP ports. This ensures the client and server communicate correctly without connection refused errors.
from mcp.server.stdio import stdio_server
from mcp.server import Server
import threading
import time
# Start MCP stdio server in a background thread
server = Server()
threading.Thread(target=stdio_server, args=(server,), daemon=True).start()
# Give server time to start
time.sleep(1)
# Now client code can connect to the running stdio server
# Example client usage would follow here
print("MCP stdio server started successfully.") MCP stdio server started successfully.
Preventing it in production
Implement robust startup checks to ensure the MCP server is running before clients connect. Use retries with exponential backoff on connection attempts. Validate transport configuration to avoid unsupported TCP ports. Monitor logs for connection errors and alert on failures to maintain uptime.
Key Takeaways
- Always start the MCP server before connecting the client to avoid connection refused errors.
- Use stdio or SSE transport for MCP communication; do not use TCP ports like 25565.
- Implement retries and validation in production to handle transient connection issues.