← All articles

MCP Failed to Connect: Causes and Fixes

July 7, 2026·22 min read·MCPForge

Quick Answer

When MCP fails to connect, the fix depends on where the connection breaks — not on random configuration changes.

For local stdio servers: Run the exact configured command manually in your terminal. If it fails, fix the command first. If it runs, check whether the process exits immediately (crash or missing dependency) or stays alive. If it stays alive, check whether the server writes anything unexpected to stdout (which corrupts the protocol). Then verify the MCP initialization handshake with MCP Inspector.

For remote HTTP servers: Confirm the URL resolves, the endpoint is reachable, the correct transport is configured, authentication credentials are valid, and the MCP initialization handshake succeeds after the HTTP connection is established.

Do not guess the fix. Find the stage where the connection fails.

The goal is not to try every possible fix. The goal is to identify the first failing stage and fix only that layer.


If the failing server is specifically a Shadcn MCP implementation, use the Shadcn MCP failed to connect guide after confirming the general connection stage.

MCP Failed to Connect: 60-Second Checklist

Work through this in order. Stop when you find the failure.

  • Is this a local stdio server or a remote HTTP server?
  • For stdio: run the exact configured command manually — does it work?
  • For remote: can you reach the endpoint with curl or a browser?
  • What is the first real error message in client or server logs?
  • Does the executable exist and resolve correctly outside the MCP client?
  • Are command and arguments exactly correct (paths, quoting, flags)?
  • Are all required environment variables set and non-empty?
  • Is the working directory correct for any relative paths the server uses?
  • Does the stdio server process exit immediately (crash/missing dependency)?
  • Does the stdio server write anything to stdout other than JSON-RPC messages?
  • For remote: is the URL correct, including protocol, hostname, and path?
  • For remote: what HTTP status code is returned?
  • Are authentication credentials configured correctly and not expired?
  • Do client and server logs show where the failure occurs?
  • Does MCP Inspector successfully initialize with this server?
  • Have you reduced the problem to a single server with minimal configuration?

Jump to the Right Fix

Error or SymptomStart Here
command not foundVerify the executable and PATH
spawn ENOENTCheck command, absolute path, and runtime
Server exits immediatelyInspect stderr and exit code
Works in terminal but fails in clientCheck PATH, environment variables, and working directory
Missing API keyVerify environment variables
JSON parse or initialization failureCheck stdout contamination and MCP initialization
ECONNREFUSEDCheck remote server availability and port
DNS errorCheck hostname and DNS resolution
HTTP 401Check authentication
HTTP 403Check authorization and permissions
HTTP 404Verify the MCP endpoint URL
HTTP 429Check rate limits and retry behavior
HTTP 5xxCheck server logs and service status
TimeoutCheck network path, server latency, and cold starts
Inspector works, but client failsCompare client config, env, transport, and lifecycle behavior; if the Inspector UI cannot reach its proxy, fix the MCP Inspector proxy connection first
Connects but no tools appearDebug tool discovery, not connection

Want to analyze your API security?

Import your OpenAPI spec and generate a Security Report automatically.

What "MCP Failed to Connect" Actually Means

"MCP failed to connect" is a client-reported summary, not a precise error. In Cursor, first separate server-specific MCP failures from a broader Cursor connection error. It means the MCP client could not successfully start, reach, authenticate with, initialize, or maintain a connection to the MCP server. The failure could be at any of six or more distinct stages.

The critical insight is this: the fix for a process launch failure is completely different from the fix for an authentication failure, which is completely different from the fix for stdout contamination. Applying the wrong fix wastes time and sometimes makes diagnosis harder.

Local stdio servers run as child processes launched by the MCP client. The client starts the process, attaches to stdin/stdout, and exchanges JSON-RPC messages over those streams. Failures are usually about process execution, environment, or protocol stream integrity.

Remote HTTP servers run independently and expose an HTTP endpoint. The client connects over the network and communicates via HTTP. Failures are usually about network reachability, URL correctness, authentication, or HTTP transport configuration.

These are fundamentally different deployment models and require different diagnostic approaches.


First: Identify Where the MCP Connection Fails

Follow this decision tree before touching any configuration:

MCP client reports "failed to connect"
            |
            v
    Local stdio or remote HTTP?
            |
     ________+_________
    |                   |
    v                   v
Local stdio         Remote HTTP
    |                   |
    v                   v
Can the configured  Is the endpoint
command execute?    reachable?
    |                   |
   No                  No
    |                   |
    v                   v
Fix command,        Fix URL, DNS,
PATH, or runtime    firewall, or server
    |
   Yes
    |
    v
Does the process
stay alive?
    |
   No
    |
    v
Inspect stderr and  <-- crash, missing dep,
exit code               config validation
    |
   Yes
    |
    v
Does MCP initialize?
    |
   No
    |
    v
Check stdout contamination,   <-- most common
protocol message format,          overlooked cause
initialization crash
    |
   Yes                         Remote HTTP continued:
    |                              |
    v                              v
Connection established.       Is auth required?
Investigate tool discovery        |
or session-level failures.       Yes
                                   |
                                   v
                              Verify credentials,
                              token expiry,
                              OAuth flow
                                   |
                                  OK
                                   |
                                   v
                              Does MCP initialize?
                              If not: transport
                              mismatch or server bug

MCP Connection Lifecycle: Find the Exact Failure Stage

Every MCP connection passes through these stages. A failure at any stage produces a "failed to connect" message in the client, but the root cause and fix are stage-specific.

Failure StageTypical SymptomHow to VerifyWhat to Fix
1. Configuration loadingClient refuses to start or shows config parse errorRead client error output; validate JSON syntaxFix JSON syntax, required fields, config file location
2. Command execution / network connection"command not found", "spawn error", "ECONNREFUSED"Run command manually; curl the endpointFix PATH, executable path, URL, or network
3. Server startup / endpoint reachabilityProcess exits immediately; HTTP timeout or DNS failureCheck exit code, stderr; ping/curl endpointFix crash, missing deps, DNS, firewall
4. Transport establishmentConnection hangs or immediate disconnectTest with MCP Inspector; check HTTP statusFix transport config, HTTP vs HTTPS, proxy
5. AuthenticationHTTP 401/403; auth error in logsCheck HTTP response body; inspect credentialsFix API key, bearer token, OAuth config
6. MCP initialization handshakeProcess alive, HTTP reachable, but client reports failureTest with MCP Inspector; inspect stdout for contaminationFix stdout contamination, protocol message format
7. Capability negotiationConnects but tools/resources missingInspector shows initialization succeeds but empty capsFix server capability registration
8. Session operationConnects, then dropsClient and server logs after initializationFix timeout, keepalive, memory, upstream failures

Fix Local MCP Servers That Failed to Connect

1. Run the Exact Server Command Manually

This is usually the highest-value first diagnostic step for local stdio connection failures.

Copy the command and args from your MCP configuration exactly. Open a terminal and run them:

bash
# npx-based server
npx -y @modelcontextprotocol/server-filesystem /tmp

# Node.js server
node /home/user/my-mcp-server/dist/index.js

# Python server
python -m my_mcp_server --config ./config.json

# uvx-based server
uvx mcp-server-git --repository /path/to/repo

Interpreting the result:

What you seeWhat it means
command not foundExecutable not in PATH or not installed
Cannot find module / ModuleNotFoundErrorMissing dependency — install it
Python interpreter not foundWrong python path or missing runtime
Immediate exit, no outputCrash — check exit code and stderr
Exit with error messageRead the message — it tells you exactly what is wrong
Silent, appears to hangThis is normal — stdio server is waiting for JSON-RPC input

A stdio MCP server that stays running silently may simply be waiting for protocol input. Silence alone does not prove that initialization will succeed. It is waiting for the client to send the initialize request on stdin. This is not a hang.

2. Verify the Executable Exists and Is Available to the MCP Client

Desktop applications may inherit a different PATH and environment than your terminal, depending on the operating system and how the app was launched. If a command works in your terminal but fails in the MCP client, verify the executable path explicitly.

macOS/Linux:

bash
# Which node is your terminal using?
command -v node
node --version

# Which npx?
command -v npx

# Which python?
command -v python3
python3 --version

# Which uvx?
command -v uvx

Windows PowerShell:

powershell
# Find where node is
Get-Command node | Select-Object -ExpandProperty Source

# Find npx
Get-Command npx | Select-Object -ExpandProperty Source

# Find python
Get-Command python | Select-Object -ExpandProperty Source

# Show current PATH
$env:PATH -split ";"

If the resolved path is something like /Users/you/.nvm/versions/node/v20.11.0/bin/node, your MCP client may not be able to resolve node by name. Use the absolute path in your MCP configuration instead:

json
{
  "mcpServers": {
    "my-server": {
      "command": "/Users/you/.nvm/versions/node/v20.11.0/bin/node",
      "args": ["/Users/you/my-mcp-server/dist/index.js"]
    }
  }
}

3. Check the MCP Command and Arguments

Common configuration mistakes:

json
// WRONG: shell syntax in command (& is PowerShell/cmd specific)
{ "command": "node && npm start" }

// WRONG: relative path that only works from one directory
{ "command": "node", "args": ["./dist/index.js"] }

// WRONG: combined command + args in command field
{ "command": "npx @modelcontextprotocol/server-filesystem /data" }

// CORRECT
{
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"]
}

// CORRECT JSON representation of a Windows path
{ "command": "C:\\Program Files\\nodejs\\node.exe" }

// Also commonly accepted by many tools
{ "command": "C:/Program Files/nodejs/node.exe" }

Key rules:

  • command must be a single executable, never a shell pipeline
  • args is an array where each element is one argument
  • Paths should be absolute when the server will be launched from an unknown working directory
  • Shell builtins (source, export, &&) do not work in command — they require a shell wrapper

4. Verify Environment Variables

Many MCP servers require API keys or configuration values via environment variables. These are available in your terminal but often invisible to GUI-launched processes.

Check whether required variables exist in your session:

bash
# macOS/Linux — check without printing the value
[ -z "$OPENAI_API_KEY" ] && echo "NOT SET" || echo "SET (length: ${#OPENAI_API_KEY})"
powershell
# Windows PowerShell
if ([string]::IsNullOrEmpty($env:OPENAI_API_KEY)) { "NOT SET" } else { "SET (length: $($env:OPENAI_API_KEY.Length))" }

Declare required environment variables in the MCP client's env block:

json
{
  "mcpServers": {
    "my-server": {
      "command": "/usr/local/bin/node",
      "args": ["/home/user/my-mcp-server/dist/index.js"],
      "env": {
        "OPENAI_API_KEY": "sk-...",
        "LOG_LEVEL": "info"
      }
    }
  }
}

⚠️ Do not put credentials directly in args. Environment variables are the correct mechanism. Always verify your configuration file is not committed to version control.

5. Check the Working Directory

The working directory used to launch a stdio server depends on the MCP client and configuration. Do not assume it is the same directory where you tested the command manually. This breaks:

  • Config file loading (./config.json)
  • Relative database paths
  • File watchers with relative patterns
  • Credential files with relative paths

Fix this by using absolute paths in your server code and configuration, or by explicitly setting cwd where your client supports it:

json
{
  "mcpServers": {
    "my-server": {
      "command": "/usr/local/bin/node",
      "args": ["/home/user/my-mcp-server/dist/index.js"],
      "cwd": "/home/user/my-mcp-server"
    }
  }
}

6. Check Whether the Server Exits Immediately

Capture stderr and the exit code directly:

bash
# macOS/Linux — run server and capture both stdout and stderr
node /path/to/server/dist/index.js 2>/tmp/mcp-server-stderr.log
echo "Exit code: $?"
cat /tmp/mcp-server-stderr.log
powershell
# Windows PowerShell
$p = Start-Process -FilePath "node" -ArgumentList "C:\path\to\server\dist\index.js" `
     -RedirectStandardError "$env:TEMP\mcp-stderr.txt" -Wait -PassThru
$p.ExitCode
Get-Content "$env:TEMP\mcp-stderr.txt"

Common causes of immediate exit:

  • Uncaught exception on startup (check stack trace in stderr)
  • Missing required environment variable (server validates on startup and exits)
  • package.json main field pointing to a file that does not exist
  • Missing node_modules — run npm install in the server directory
  • Python package not installed — run pip install -r requirements.txt
  • A port conflict on a server that opens a local port before handling stdio

7. Check stdout Contamination — The Most Overlooked Cause

This is one of the most important causes to check when a stdio server starts, but initialization fails. The process launches and stays running, but the MCP client cannot parse the protocol.

Why it happens: stdio MCP servers use stdout as an exclusive JSON-RPC message channel. For stdio MCP servers, stdout is used for protocol messages. Non-protocol output on stdout can corrupt the message stream and cause initialization or parsing failures.

Common mistakes in TypeScript/JavaScript:

typescript
// WRONG — corrupts the protocol stream
console.log('MCP server started');
console.log(`Loaded ${tools.length} tools`);

// CORRECT — stderr is safe
console.error('MCP server started');
process.stderr.write(`Loaded ${tools.length} tools\n`);

Common mistakes in Python:

python
# WRONG
print("Server initialized")
logging.basicConfig()  # defaults to stderr, but verify

# CORRECT
import sys
print("Server initialized", file=sys.stderr)
logging.basicConfig(stream=sys.stderr)

How to test for stdout contamination:

bash
# Run the server and immediately send Ctrl+C after a moment.
# Look at stdout — anything other than silence is a problem.
node /path/to/server/dist/index.js 2>/dev/null | head -5

If you see any text output before you have sent any input, that output will be received by the MCP client before any valid JSON-RPC message, and initialization will fail.

8. Verify MCP Initialization

If the server process starts and stays alive, but the client still reports a connection failure, the problem is in the initialization handshake. Causes include:

  • The server sends malformed JSON-RPC on the first message
  • The server expects a different protocol version
  • The server crashes when it receives the initialize request
  • The server implementation has a bug in its initialize handler

Use MCP Inspector to test this in isolation (see dedicated section below).


Fix Remote MCP Servers That Failed to Connect

1. Verify the Exact MCP Server URL

Confirm you are using the correct endpoint. Common mistakes:

  • Using the service homepage (https://api.example.com/) instead of the MCP endpoint (https://api.example.com/mcp)
  • HTTP instead of HTTPS
  • Wrong port
  • Outdated endpoint from old documentation

Test basic reachability:

bash
# macOS/Linux
curl -sv https://your-mcp-server.example.com/mcp 2>&1 | head -50
powershell
# Windows PowerShell
Invoke-WebRequest -Uri "https://your-mcp-server.example.com/mcp" -Method GET

Getting any HTTP response does not confirm MCP compatibility. You need the correct endpoint that handles MCP protocol requests, not just one that returns HTTP 200.

2. Check DNS and Network Reachability

bash
# macOS/Linux DNS check
nslookup your-mcp-server.example.com
dig your-mcp-server.example.com +short

# TCP connectivity check
nc -zv your-mcp-server.example.com 443

# Full HTTPS reachability
curl -sv --max-time 10 https://your-mcp-server.example.com/mcp
powershell
# Windows PowerShell
Resolve-DnsName your-mcp-server.example.com
Test-NetConnection -ComputerName your-mcp-server.example.com -Port 443

3. HTTP Status Codes and What They Mean

HTTP StatusLikely MeaningNext Check
No response / ECONNREFUSEDServer not running or port not openCheck server deployment, firewall rules
Connection timeoutNetwork path blocked or server unreachableCheck VPN, firewall, proxy, server logs
400 Bad RequestRequest format rejectedCheck transport configuration and headers
401 UnauthorizedMissing or invalid credentialsCheck API key, bearer token, OAuth config
403 ForbiddenCredentials valid but access deniedCheck permissions, IP allowlist, plan limits
404 Not FoundEndpoint path is wrongVerify exact MCP endpoint URL
405 Method Not AllowedWrong HTTP method for this endpointCheck the server documentation and transport configuration
429 Too Many RequestsRate limitedBack off, check rate limit headers
500/502/503/504Server-side errorCheck server logs, service status page

4. Verify the Transport

The current MCP specification defines Streamable HTTP as the standard HTTP transport. It uses POST requests to a single endpoint. Legacy implementations used HTTP+SSE (separate GET/POST endpoints).

A transport mismatch — where your client sends Streamable HTTP requests but the server expects the legacy SSE transport, or vice versa — will produce connection failures that look like HTTP errors or protocol errors.

Verify which transport your server supports (check its documentation or source code) and ensure your client is configured to match. If the server is legacy SSE-based, your client configuration may need to specify the SSE transport explicitly — but only do this if the server documentation confirms it.

5. Verify Authentication

Check authentication configuration carefully:

bash
# Test with a bearer token
curl -sv https://your-mcp-server.example.com/mcp \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0.0.1"}}}'

Distinguish between:

  • Connection failure — server unreachable (DNS, network, firewall)
  • Authentication failure — server reachable, HTTP 401 returned
  • Authorization failure — server reachable, credentials valid, HTTP 403 returned (wrong permissions)

For OAuth-protected MCP servers, the client must complete the OAuth authorization code flow before the MCP connection. OAuth metadata discovery failures (the client cannot reach /.well-known/oauth-authorization-server) produce their own category of error. Check the authorization server and protected resource metadata required by the MCP authorization flow used by that server. Do not assume every server exposes the same discovery endpoint.

6. TLS, Proxy, VPN, and Firewall Issues

  • Certificate validation failure: curl -sv will show SSL certificate problem. Check whether a corporate proxy is intercepting TLS and substituting its own certificate. Contact your network team — do not disable certificate verification in production.
  • HTTP proxy: Set HTTPS_PROXY or HTTP_PROXY environment variables if your environment requires a proxy, but verify your MCP client respects these variables.
  • VPN: If the MCP server is on a private network, confirm VPN is connected and routing the relevant subnet.
  • Corporate firewall: Test from a different network to isolate. If the server works from a mobile hotspot but not from the corporate network, the firewall is the issue.

7. Timeouts and Server Availability

A slow response that eventually times out is different from an immediate rejection:

  • Immediate ECONNREFUSED: server is not running or port is not open
  • TCP connect succeeds but no HTTP response: server is overloaded, in a bad state, or TLS is failing
  • HTTP response eventually returns: cold start (serverless deployment), upstream dependency failure

Check the server's status page or dashboard. For serverless deployments, cold starts can exceed some clients' default initialization timeout.


Test the Server Independently with MCP Inspector

MCP Inspector is the official tool for testing MCP servers independently of any client. Use it whenever you cannot tell whether the problem is in the server or the client configuration.

Install and run:

bash
npx @modelcontextprotocol/inspector

This opens a browser-based UI (typically at http://localhost:5173). From there you can:

  • Configure a stdio server with the exact command and args
  • Connect to a remote HTTP endpoint
  • Observe the full initialization handshake
  • List tools, resources, and prompts
  • Send test requests

Interpreting Inspector results:

Inspector ResultWhat It Means
Cannot launch the server commandProblem with command, PATH, or executable — not a protocol issue
Launches but initialization failsstdout contamination, protocol error, or server bug
Initializes but shows no toolsServer exposes no tools, or tool registration failed
Inspector works, your client does notClient configuration problem — compare configs exactly
Inspector also failsConfirmed server-side problem

If Inspector connects and shows your tools correctly but your MCP client still fails, the server is likely functional, and the remaining issue is probably in the original client's configuration, environment, transport support, authentication flow, or lifecycle behavior. Compare the command, args, env, and working directory between Inspector and your client configuration character by character.


MCP Failed to Connect: Client-Specific Notes

Claude Desktop

Configuration file location:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json

Log location for MCP-related errors:

  • macOS: ~/Library/Logs/Claude/
  • Windows: %APPDATA%\Claude\logs\

Key checks: Claude Desktop launches stdio servers as child processes. GUI PATH differences are a primary cause of failures here. Use absolute paths for command. After changing configuration, fully quit and reopen Claude Desktop — changes are not hot-reloaded.

Claude Code

Claude Code (the CLI) provides the claude mcp command family for managing MCP servers. Check claude mcp list to confirm server registration. Use claude mcp add to add servers or edit the configuration directly. Claude Code may show more detailed error output in the terminal compared to the desktop app, making it easier to see early failure messages.

Cursor

Cursor's MCP configuration lives in .cursor/mcp.json (project-scoped) or in global settings. MCP server errors appear in the Cursor output panel. Cursor's PATH environment has the same GUI-vs-terminal differences as other desktop applications — use absolute paths.

VS Code (with GitHub Copilot or MCP extensions)

VS Code MCP configuration uses the workspace or user settings.json. Check the Output panel and select the relevant MCP channel for diagnostic messages. VS Code inherits PATH from how it was launched (from a terminal vs from a desktop icon) — launching VS Code from the terminal (code .) gives it your shell PATH, which can resolve some executable-not-found issues during development.


Common MCP Connection Failure Scenarios

SymptomMost Likely StageFirst CheckLikely Fix
command not foundCommand executioncommand -v <executable>Use absolute path
Server exits immediately, no outputProcess startupRun manually, check stderrFix crash, install deps
Works in terminal, fails in GUI appCommand executionGet-Command / command -vAbsolute path + explicit env vars
Missing API key errorConfiguration / startupCheck env var in client configAdd to env block
Server running but client never connectsInitializationCheck stdout for contaminationMove logs to stderr
Non-JSON output on stdoutInitializationRun server, pipe stdout to headFix all console.log calls
Remote: DNS resolution failureNetworknslookup / Resolve-DnsNameFix hostname or DNS
Remote: ECONNREFUSEDNetwork / serverIs the server running?Start server, fix port/firewall
HTTP 401AuthenticationCheck credentials in configFix API key / bearer token
HTTP 403AuthorizationCredentials valid? Permissions?Fix permissions or plan
HTTP 404URL correctnessCheck exact endpoint pathFix URL in config
HTTP 429Rate limitingCheck rate limit headersBack off, reduce request rate
HTTP 5xxServer errorCheck server logs / status pageContact server operator
OAuth metadata failureAuthentication setupCurl /.well-known/oauth-authorization-serverFix OAuth server config
Connection timeoutNetwork / cold startTest-NetConnection, curl timingCheck firewall, cold start
Inspector connects, client does notClient configurationCompare config character by characterFix client config
Connects but no tools listedCapability negotiationInspector tools tabFix server tool registration
Connection drops after initializationSessionClient and server logs post-initFix keepalive, timeout, memory

Windows-Specific MCP Connection Fixes

Find where executables are:

powershell
# Find node.exe full path
Get-Command node | Select-Object -ExpandProperty Source
# Output: C:\Program Files\nodejs\node.exe

# Find npx
Get-Command npx | Select-Object -ExpandProperty Source

# Find python
Get-Command python | Select-Object -ExpandProperty Source

# Alternative: where.exe
where.exe node
where.exe python

Test network connectivity:

powershell
# TCP port test
Test-NetConnection -ComputerName your-server.example.com -Port 443

# DNS resolution
Resolve-DnsName your-server.example.com

# HTTP request
Invoke-RestMethod -Uri "https://your-server.example.com/mcp" -Method Get

PATH differences for GUI apps: The Windows GUI application PATH is set at login and does not include paths added by nvm, user-level npm installs, or tools installed via Chocolatey/Scoop in user-profile scripts. The safest fix is to use absolute paths from Get-Command output in your MCP configuration.

Paths with spaces: JSON requires backslash escaping. Use forward slashes or double-escaped backslashes:

json
{ "command": "C:/Program Files/nodejs/node.exe" }

WSL boundary: If your MCP server lives in a WSL filesystem, you cannot run it directly with node.exe pointing into \\wsl$\... paths reliably. Either run the server inside WSL and use WSL's npx/node, or keep server files in the Windows filesystem.


macOS and Linux MCP Connection Fixes

bash
# Confirm which executable will be used
command -v node
command -v npx
command -v python3
command -v uvx

# Check executable permissions
ls -la /path/to/server/dist/index.js
# Should have execute permission if run directly, read permission for node

# Check file exists
[ -f /path/to/server/dist/index.js ] && echo "exists" || echo "MISSING"

# Current working directory test
pwd
# Run server from its own directory
cd /path/to/server && node dist/index.js

# DNS check
nslookup your-server.example.com
dig +short your-server.example.com

# HTTPS reachability with timing
curl -sv --max-time 15 https://your-server.example.com/mcp 2>&1

# Capture exit code and stderr together
node /path/to/server/dist/index.js 2>&1 1>/dev/null; echo "Exit: $?"

Shell initialization files and PATH: If command -v node finds node in your terminal but the MCP client cannot, check what added it to PATH. Common culprits: nvm adds its shim to .bashrc or .zshrc. Homebrew on Apple Silicon installs to /opt/homebrew/bin, which some GUI apps do not have in PATH. Add the absolute path to your MCP configuration as the permanent fix.


MCP Failed to Connect After It Worked Before

Regressions have a specific cause. Do not modify configuration before identifying what changed.

Regression checklist:

  • Was a package or dependency updated? (npm outdated, pip list --outdated)
  • Was the MCP client updated?
  • Did credentials expire? (API keys, OAuth tokens)
  • Were environment variables changed or removed?
  • Was the server file moved, renamed, or the repo restructured?
  • Was the remote endpoint URL changed?
  • Was a new server version deployed with a breaking change?
  • Did the MCP protocol specification version change in a client update?
  • Is there an upstream service outage?
  • Did the network environment change (new VPN, corporate proxy, new machine)?

Approach: Use git log, npm ls, changelog entries, and deployment history to find what changed. Fix the specific change before touching anything else. If a dependency update broke the server, pinning or upgrading to a fixed version is more reliable than reconfiguring the client.


MCP Connects but Tools Do Not Appear

This is a different problem from connection failure. If MCP Inspector shows a successful initialization, the connection is working. Missing tools indicate a capability issue:

  • The server completed initialization but its tool registration code threw an error after initialization
  • The server explicitly exposes no tools (only resources or prompts)
  • The tools/list request fails or returns an empty array
  • The client UI has not refreshed since initialization

Check Inspector's Tools tab. If Inspector also shows no tools, the issue is in the server's tool registration. If Inspector shows tools but your client does not, it may be a client UI refresh issue or a client-side filtering issue.

Do not apply connection-layer fixes to a missing-tools problem. They are different failure classes.


MCP Error Type Comparison

Before debugging, confirm you are debugging the right failure type:

Failure TypeConnection Established?Typical SymptomWhat to Debug
Process launch failureNo"spawn error", "command not found"Command, PATH, executable, environment
Network connection failureNoECONNREFUSED, DNS error, timeoutURL, DNS, firewall, server availability
Transport failureNo / partialHTTP error, protocol parse errorTransport config, HTTP headers, method
Authentication failurePartial (HTTP works)HTTP 401/403Credentials, token expiry, OAuth flow
MCP initialization failureNo (protocol level)Handshake error, parse failurestdout contamination, protocol version, server bug
Tool discovery failureYesNo tools, empty listServer tool registration, permissions
Tool execution failureYesError on specific tool callTool handler, upstream API, permissions

If you are applying connection fixes to a tool execution error, stop. The connection is fine.


Minimal Reproduction Procedure

For local stdio servers:

  1. Create a minimal MCP config with only the one failing server
  2. Use the exact command and args from your configuration
  3. Include only the environment variables the server actually requires
  4. Run the command manually in a terminal: does it start?
  5. If it starts: does it produce any stdout output immediately? (Should produce none)
  6. Run MCP Inspector with the same command and args
  7. Does Inspector initialize? Does it show tools?
  8. If Inspector works: compare your client configuration with Inspector configuration exactly

For remote HTTP servers:

  1. Confirm exact URL with curl -sv
  2. Confirm DNS with nslookup / Resolve-DnsName
  3. Confirm HTTP reachability and status code
  4. Confirm authentication with a manual request including credentials
  5. Send a manual MCP initialize JSON-RPC request with curl
  6. Verify the response is a valid MCP InitializeResult
  7. Compare this working request with what your client configuration would produce

Each step either confirms the previous layer works or identifies the exact failure point. Do not proceed to the next step until the current one confirms correctly.


What to Collect Before Reporting an MCP Connection Bug

Before opening a GitHub issue or posting for help, collect this information. It prevents back-and-forth and helps the maintainers reproduce the problem immediately.

Required information:

  • MCP client name and exact version
  • MCP server name and exact version (or commit hash)
  • Operating system and version
  • Local stdio or remote HTTP
  • Transport type (stdio / Streamable HTTP / SSE)
  • Sanitized configuration (remove all API keys, tokens, secrets)
  • Exact command and arguments
  • First complete error message
  • Process exit code (for stdio)
  • Relevant stderr logs from the server
  • HTTP status code and response body (for remote)
  • Whether MCP Inspector reproduces the failure
  • Minimal reproduction steps
  • What changed before the failure started (if regression)
  • Expected behavior vs actual behavior

⚠️ Before posting anywhere: Remove API keys, bearer tokens, OAuth secrets, database credentials, personal email addresses, internal hostnames, and any other sensitive information from logs and configuration. Sanitize, then post.


MCP Connection Problem Prevention

These practices prevent most MCP connection failures before they happen:

  • Always use absolute paths for executables and server files in MCP configuration
  • Always declare required environment variables in the MCP client's env block, not as system environment variables
  • Never write to stdout in stdio MCP servers — use stderr for all logging
  • Run your server manually after every update before testing in a client
  • Pin dependency versions in production server packages to prevent unexpected breakage
  • Store configuration in version control so you know exactly what changed
  • Test with MCP Inspector after any server change before deploying
  • Check server logs after client updates, not just after server changes

For teams deploying MCP servers to production, see the running MCP in production guide for architecture, monitoring, and reliability considerations beyond the initial connection.

If you are building or publishing an MCP server and want to verify it correctly implements the protocol before users encounter connection failures, the MCPForge verification tool tests your server against the official MCP specification.


References

Frequently Asked Questions

Why does my MCP server fail to connect?

The most common causes are: the configured command cannot be found or executed, the server process exits immediately due to a crash or missing dependency, environment variables are missing (especially API keys), or the MCP initialization handshake fails because of stdout contamination. Start by running the exact configured command manually in your terminal to see the real error.

How do I know whether my MCP server is actually running?

For stdio servers, run the exact command from your MCP configuration directly in a terminal. If it starts without error and appears to wait silently, that is normal — stdio servers block waiting for JSON-RPC input. Use MCP Inspector to send a real initialization handshake and confirm the server responds. For remote servers, check the process manager, container logs, or service dashboard.

Why does my MCP server work in the terminal but fail in Claude Desktop, Cursor, or VS Code?

GUI applications inherit a different PATH and environment than your terminal session. The executable may be found when you type it in a shell but invisible to a GUI-launched process. The fix is to use absolute paths in your MCP configuration and explicitly declare all required environment variables in the client's env configuration block.

Can logging to stdout break an MCP stdio server?

Yes. stdio MCP servers use stdout exclusively for JSON-RPC protocol messages. Any other output — startup banners, debug logs, progress output, or third-party library output — corrupts the protocol stream and will cause the client to fail initialization. All diagnostic output must go to stderr.

What does HTTP 401 mean when connecting to an MCP server?

HTTP 401 means the server received your request but rejected it because no valid credentials were provided. Check that your API key or bearer token is correctly configured, not expired, and sent in the correct header format. Do not confuse 401 (no valid credentials) with 403 (credentials valid but access denied).

Why does MCP Inspector connect successfully when my MCP client does not?

This strongly suggests a client-specific configuration, environment, compatibility, or lifecycle issue, not a server problem. The server works correctly when launched properly. Check the exact command, arguments, environment variables, and working directory in your client configuration. The difference between Inspector and your client is usually in how the server is launched, not in the protocol itself.

How do I test an MCP server connection without my MCP client?

Use MCP Inspector: run `npx @modelcontextprotocol/inspector` and configure it to launch or connect to your server. Inspector handles the full MCP initialization handshake, shows capabilities, and lets you list tools and resources. This isolates server behavior from client configuration entirely.

Why does my MCP server connect but show no tools?

A missing tools list is not a connection failure — it is a capability or tools/list issue. The connection and initialization succeeded. Check whether the server actually exposes tools (some servers only expose resources or prompts), whether the tool registration code ran without error, and whether your client correctly loaded the tools after initialization.

Should I reinstall the MCP server to fix a connection failure?

Reinstalling should not be your first step. It fixes one specific cause — a corrupted installation — but wastes time if the real problem is a wrong path, a missing environment variable, or stdout contamination. Identify the failure stage first. If running the command manually gives a module-not-found error, then reinstalling is the correct fix.

How do I know whether authentication is causing the MCP connection failure?

Check the HTTP status code. A 401 response indicates authentication failure. A connection-refused or DNS-resolution error happens before authentication and is a network or URL problem. A successful HTTP connection followed by MCP initialization failure may indicate an authorization problem at the protocol level. These are three different failure stages requiring different fixes.

Check your MCP security posture

Generate a Security Score, detect risky tools, and review permissions before exposing APIs to AI agents.