ConnectionRefusedError
asyncio.exceptions.ConnectionRefusedError
Stack trace
Traceback (most recent call last):
File "mcp/server/transport/sse.py", line 87, in _connect
await self._session.connect()
File "aiohttp/client.py", line 1234, in _request
raise ConnectionRefusedError('Connection refused')
asyncio.exceptions.ConnectionRefusedError: Connection refused Why it happens
This error occurs when the MCP server attempts to establish a Server-Sent Events (SSE) connection but the target server or endpoint refuses the connection. Common causes include the server being down, incorrect endpoint URL, firewall blocking, or network issues preventing the TCP handshake.
Detection
Monitor connection attempts to the SSE endpoint and catch ConnectionRefusedError exceptions to log detailed connection failure reasons before the server crashes.
Causes & fixes
The MCP server is trying to connect to an incorrect or unreachable SSE endpoint URL.
Verify and correct the SSE endpoint URL in your MCP server configuration to point to the valid and reachable SSE server.
The SSE server is down or not running, refusing incoming connections.
Ensure the SSE server is running and accepting connections on the expected port before starting the MCP server.
A firewall or network policy is blocking the TCP connection to the SSE server port.
Configure firewall and network rules to allow outbound TCP connections from the MCP server to the SSE server port.
The MCP server's network environment has DNS resolution issues causing connection attempts to fail.
Check and fix DNS settings or use IP addresses directly to avoid DNS resolution failures.
Code: broken vs fixed
import asyncio
async def connect_sse():
# This will raise ConnectionRefusedError if server is unreachable
await session.connect('http://wrong-url:8000/sse') # bad URL causes connection refused
asyncio.run(connect_sse()) import os
import asyncio
async def connect_sse():
sse_url = os.environ.get('SSE_ENDPOINT', 'http://localhost:8000/sse') # fixed URL from env
await session.connect(sse_url) # fixed URL to reachable SSE server
asyncio.run(connect_sse()) # environment variable controls endpoint Workaround
Wrap the SSE connection call in try/except ConnectionRefusedError and implement a retry with exponential backoff to handle temporary unavailability.
Prevention
Implement health checks for the SSE server before MCP server startup and use environment-configured endpoints with network policies verified to allow SSE connections.