You build an MCP server, run it in your terminal, and it starts without a single error. Then you add it to Claude Desktop, Claude Code or Cursor and it shows up as failed, disconnected, or connected with zero tools. Almost every time, the cause is one of a small set of problems with how stdio servers are launched and how they talk to the client. This post walks through each one with broken and fixed code.
TL;DR
- Over stdio, stdout belongs to the protocol. Any stray
print(),console.log, banner or progress message breaks the JSON-RPC stream. Send all logs to stderr. - The client launches your server from a different directory, with a different environment. Use absolute paths for the command, the script and any files you read.
- GUI apps often don't see your shell's PATH, so
nvm,pyenvanduvinstalls go missing. Use absolute command paths or setenvin the config. - Missing API keys and slow startup work (loading models, connecting to databases) crash or time out the handshake. Fail with a clear message on stderr, and load heavy things lazily.
- Debug with the MCP Inspector, the client's MCP logs, and a manual
initializerequest piped into the server.
How the stdio transport works
With the stdio transport there is no port and no HTTP. The client (the host app) starts your server as a child process and then:
- Writes JSON-RPC messages to the server's stdin, one message per line.
- Reads JSON-RPC messages from the server's stdout, one message per line.
- Treats the server's stderr as a side channel for logs. Most clients capture it into a log file.
The first exchange is the handshake: the client sends initialize, the server replies with its capabilities, and the client sends a notifications/initialized notification. Only after that does the client call tools/list. If anything goes wrong before or during this handshake (the process can't start, exits early, writes garbage to stdout or takes too long) the client marks the server as failed.
That model explains nearly every bug below: stdout is a wire format, and the process runs in an environment you didn't set up.
Cause 1: Writing to stdout
This is the classic one. Every line on stdout must be a complete JSON-RPC message. A single print("Server starting...") gives the client a line it can't parse, and depending on the client you get a parse error, a dropped connection or a server that silently never finishes initializing.
Python
Broken:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("weather")
print("Weather server starting...") # goes to stdout and corrupts the stream
@mcp.tool()
def get_forecast(city: str) -> str:
"""Return a short forecast for a city."""
print(f"Looking up {city}") # also stdout, also breaks things
return f"Sunny in {city}"
if __name__ == "__main__":
mcp.run()Fixed: configure logging to write to stderr, and use file=sys.stderr for any quick debug prints.
import logging
import sys
from mcp.server.fastmcp import FastMCP
logging.basicConfig(
level=logging.INFO,
stream=sys.stderr,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger("weather")
mcp = FastMCP("weather")
@mcp.tool()
def get_forecast(city: str) -> str:
"""Return a short forecast for a city."""
log.info("Looking up %s", city)
print("debug: quick print", file=sys.stderr)
return f"Sunny in {city}"
if __name__ == "__main__":
log.info("Weather server starting")
mcp.run()The same rules apply to the standalone fastmcp package.
Node.js
In Node, console.log, console.info and console.debug write to stdout. Only console.error and console.warn write to stderr.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new McpServer({ name: "weather", version: "1.0.0" });
const transport = new StdioServerTransport();
await server.connect(transport);
-console.log("Weather MCP server running on stdio");
+console.error("Weather MCP server running on stdio");The less obvious stdout writers
Your own print calls are easy to find. These are harder:
- npm scripts. If your config runs
npm start, npm prints a> my-server@1.0.0 startheader to stdout before your code runs. Runnode dist/index.jsdirectly, or usenpm run --silent start. - Libraries that log on import or init. Some SDKs print a banner, a deprecation notice or a "loaded config" line with a plain
print/console.log. For example, recent major versions ofdotenvlog a line when they load a.envfile. If yours does, pass{ quiet: true }toconfig(). - Progress bars and downloads. Many progress bars write to stderr (Python's
tqdmdoes by default), but not all of them. Model downloaders and CLI wrappers are common offenders. - Subprocesses. If your tool spawns a child process that inherits stdout, the child's output goes straight into the protocol stream. Capture its output instead.
In Python you can catch Python-level writes from a noisy import or setup step by redirecting them:
import contextlib
import sys
with contextlib.redirect_stdout(sys.stderr):
import noisy_sdk # anything it print()s now lands on stderr
client = noisy_sdk.Client()Note:
redirect_stdoutonly catches writes that go through Python'ssys.stdout. A C extension or child process writing directly to file descriptor 1 gets past it.
In Node, a blunt but effective safety net is to put this line at the very top of your entry file, before any other imports run:
console.log = console.error;
console.info = console.error;
console.debug = console.error;Cause 2: Relative paths and the working directory
When you run python server.py from your project folder, the current working directory is your project. When a client launches it, the working directory may be the app's install directory, your home directory or /. That breaks:
- A relative script path in the config (
"args": ["server.py"]). - Code that opens
./data/notes.dborconfig.yaml. .envloading that looks in the current directory.
Broken config:
{
"mcpServers": {
"notes": {
"command": "python",
"args": ["server.py"]
}
}
}Fixed config, using absolute paths:
{
"mcpServers": {
"notes": {
"command": "/Users/you/projects/notes-mcp/.venv/bin/python",
"args": ["/Users/you/projects/notes-mcp/server.py"]
}
}
}Inside the code, resolve files relative to the source file, not the working directory:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
DB_PATH = BASE_DIR / "data" / "notes.db"import path from "node:path";
import { fileURLToPath } from "node:url";
const baseDir = path.dirname(fileURLToPath(import.meta.url));
const dbPath = path.join(baseDir, "..", "data", "notes.db");Cause 3: PATH and environment not inherited
Your terminal has a rich environment: nvm has put a Node version on PATH, pyenv shims are set up, uv lives in ~/.local/bin, and your API keys are exported in .zshrc. A client app usually has none of that. On macOS in particular, apps launched from the Dock or Finder don't read your shell profile, so command: "npx" or command: "uv" fails with something like spawn npx ENOENT.
Find the real paths from your terminal:
which node npx uv python3Then use them in the config. With nvm there's a catch: npx is a script whose shebang calls node through PATH, so an absolute npx path alone isn't enough. Set PATH in env as well:
{
"mcpServers": {
"filesystem": {
"command": "/Users/you/.nvm/versions/node/v22.11.0/bin/npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/you/Documents"],
"env": {
"PATH": "/Users/you/.nvm/versions/node/v22.11.0/bin:/usr/local/bin:/usr/bin:/bin"
}
}
}
}For Python projects managed with uv, uv run --directory is the cleanest fix. It switches to the project directory, uses that project's environment and runs the script, so the working directory problem goes away too:
{
"mcpServers": {
"notes": {
"command": "/Users/you/.local/bin/uv",
"args": ["run", "--directory", "/Users/you/projects/notes-mcp", "server.py"],
"env": {
"NOTES_API_KEY": "your-key-here"
}
}
}
}Virtualenv not activated
"command": "python" runs whichever Python the client finds first, which is usually not your project's virtualenv. You then get ModuleNotFoundError: No module named 'mcp' in the logs and a failed server in the UI. Point command at the interpreter inside the venv (.venv/bin/python on macOS and Linux, .venv\Scripts\python.exe on Windows), or use uv run --directory as above. You never need to "activate" a venv for a subprocess. Calling its interpreter directly is enough.
Cause 4: Windows specifics
Windows has its own failure modes:
npxis a.cmdfile. Some clients spawn the command without a shell, and thennpxcan't be found. Wrap it incmd /c.- Backslashes must be escaped in JSON.
"C:\Users\you"is invalid JSON (or turns into escape sequences). Use"C:\\Users\\you"or forward slashes,"C:/Users/you", which Node and Python both accept.
{
"mcpServers": {
"filesystem": {
"command": "cmd",
"args": ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "C:\\Users\\you\\Documents"]
},
"notes": {
"command": "C:\\Users\\you\\projects\\notes-mcp\\.venv\\Scripts\\python.exe",
"args": ["C:\\Users\\you\\projects\\notes-mcp\\server.py"]
}
}
}In Claude Code you can register the same wrapper from the CLI. Everything after -- is the command and its arguments:
claude mcp add filesystem -- cmd /c npx -y @modelcontextprotocol/server-filesystem C:/Users/you/DocumentsCause 5: Crashing on startup
If the server reads an environment variable at import time and it's missing, the process dies before the handshake. Your shell had the key exported. The client doesn't.
Broken:
import os
API_KEY = os.environ["WEATHER_API_KEY"] # KeyError -> process exits immediatelyFixed: pass the key through the config's env block (as shown above) and fail with a readable message on stderr so the log tells you exactly what's wrong:
import os
import sys
API_KEY = os.environ.get("WEATHER_API_KEY")
if not API_KEY:
print(
"WEATHER_API_KEY is not set. Add it to the 'env' block of this server's MCP config.",
file=sys.stderr,
)
sys.exit(1)Tip: If the key is only needed by one tool, consider checking it inside that tool and returning a clear error instead. The server still connects, and the model can tell the user what's missing.
Cause 6: Slow startup and timeouts
Clients wait a limited time for the initialize response. If you load an embedding model, warm a cache or connect to a remote database before calling run(), the handshake can time out even though the server eventually comes up.
Broken:
from mcp.server.fastmcp import FastMCP
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2") # can take a long time on first run
mcp = FastMCP("search")Fixed: start the server first and load heavy resources on first use:
from functools import lru_cache
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("search")
@lru_cache(maxsize=1)
def get_model():
from sentence_transformers import SentenceTransformer
return SentenceTransformer("all-MiniLM-L6-v2")
@mcp.tool()
def embed(text: str) -> list[float]:
"""Return an embedding vector for the given text."""
return get_model().encode(text).tolist()Pre-download large files once from your terminal so the first tool call doesn't trigger a long download either. Claude Code also lets you raise the startup timeout with the MCP_TIMEOUT environment variable. Check the current docs for details.
Debugging tools
The MCP Inspector
The Inspector is a web UI that launches your server over stdio and lets you list and call tools by hand:
npx @modelcontextprotocol/inspector uv run --directory /Users/you/projects/notes-mcp server.pyYou can pass environment variables with -e:
npx @modelcontextprotocol/inspector -e WEATHER_API_KEY=test-key -- node /Users/you/projects/weather-mcp/dist/index.jsIt prints a localhost URL to open in your browser. If tools show up there but not in your client, the server code is fine and the problem is in the config or environment (causes 2 to 4).
Warning: The Inspector runs from your shell, so it inherits your PATH and working directory. A server that works in the Inspector can still fail in a GUI client. Always test with the same absolute paths you put in the config.
Client logs
Most clients write a log for each server that includes its stderr. That's where your tracebacks and logging output end up.
- Claude Desktop writes per-server files named like
mcp-server-<name>.log, plus a generalmcp.log, in its logs folder. On macOS that's under~/Library/Logs/Claude. On Windows it's under the Claude folder in%APPDATA%. Check the MCP debugging docs if the location has moved. - Claude Code shows server status with
claude mcp listand the/mcpcommand inside a session. Running with--debugprints more detail. - Cursor shows MCP server status and errors in its MCP settings and in the Output panel.
Following the log while you restart the client is often the fastest way to the real error:
tail -n 50 -f ~/Library/Logs/Claude/mcp-server-notes.logA manual initialize request
When you suspect stdout pollution, skip the client and talk to the server directly. This sends the handshake and a tools/list request, keeps stdin open for two seconds so the server has time to reply, and separates stdout from stderr:
{
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"manual-test","version":"0.1.0"}}}'
printf '%s\n' '{"jsonrpc":"2.0","method":"notifications/initialized"}'
printf '%s\n' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'
sleep 2
} | uv run --directory /Users/you/projects/notes-mcp server.py > stdout.log 2> stderr.logThen inspect stdout.log. Every line should be a JSON object starting with {"jsonrpc":"2.0". This snippet flags any line that isn't:
python3 -c 'import json,sys
for n, line in enumerate(open("stdout.log"), 1):
try: json.loads(line)
except ValueError: print(f"line {n} is not JSON: {line.rstrip()}")'If the server supports a different protocol version, it replies with the version it supports. That's normal negotiation, not an error. On Windows, run these commands in Git Bash or WSL.
Checklist
Go through this before you start digging into the client:
- Nothing writes to stdout except the MCP transport: no
print,console.log,console.debug, npm script header, library banner or child process output. - Logging is configured to stderr (
loggingwithstream=sys.stderr, orconsole.error). commandis an absolute path, or a name the client can definitely resolve.- Script paths in
argsare absolute, or you useuv run --directory. - File paths in code are resolved relative to the source file, not the working directory.
- The interpreter is the project's venv Python, not whatever
pythonresolves to. - Required API keys and any needed
PATHentries are set in the config'senvblock. - On Windows,
npxis wrapped incmd /cand backslashes in JSON are escaped. - Heavy setup is lazy, so
initializereturns quickly. - The server works in the MCP Inspector and with a manual
initializerequest using the exact command from your config. - You've read the client's per-server log after a fresh restart.
Once all eleven pass, the server will almost always connect, and if it still doesn't, the client log will usually show the remaining error.