All articles
MCPAIPythonNode.jsDebugging

Debugging MCP stdio Servers That Work Locally but Fail in the Client

Your MCP server runs fine in a terminal but Claude or Cursor shows it as failed. Here's why stdio servers break and how to fix each cause.

Tushar Pachouri12 min read

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, pyenv and uv installs go missing. Use absolute command paths or set env in 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 initialize request 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:

  1. Writes JSON-RPC messages to the server's stdin, one message per line.
  2. Reads JSON-RPC messages from the server's stdout, one message per line.
  3. 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.

The stdio handshake: the client must get a clean initialize reply before tools/list.

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.

Client host app Your server child process stdin: JSON-RPC from the client stdout: JSON-RPC messages only {"jsonrpc":"2.0","id":1,...} ok Server starting... not JSON stderr client log file logs, tracebacks
stdout is the protocol wire, so one printed line breaks it; logs belong on stderr.

Python

Broken:

Python
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.

Python
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.

Diff
 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 start header to stdout before your code runs. Run node dist/index.js directly, or use npm 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 of dotenv log a line when they load a .env file. If yours does, pass { quiet: true } to config().
  • Progress bars and downloads. Many progress bars write to stderr (Python's tqdm does 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:

Python
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_stdout only catches writes that go through Python's sys.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:

JavaScript
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.db or config.yaml.
  • .env loading that looks in the current directory.

Broken config:

JSON
{
  "mcpServers": {
    "notes": {
      "command": "python",
      "args": ["server.py"]
    }
  }
}

Fixed config, using absolute paths:

JSON
{
  "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:

Python
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
DB_PATH = BASE_DIR / "data" / "notes.db"
JavaScript
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.

YOUR TERMINAL GUI CLIENT LAUNCH WORKING DIRECTORY ~/projects/notes-mcp PATH nvm, pyenv shims, ~/.local/bin ENVIRONMENT API keys exported in .zshrc PYTHON the project's .venv WORKING DIRECTORY app install dir, home or / PATH no shell profile: npx, uv missing ENVIRONMENT only what the env block sets PYTHON the first python the client finds
The same command runs in a very different environment when a GUI client launches it.

Find the real paths from your terminal:

Terminal
which node npx uv python3

Then 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:

JSON
{
  "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:

JSON
{
  "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:

  • npx is a .cmd file. Some clients spawn the command without a shell, and then npx can't be found. Wrap it in cmd /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.
JSON
{
  "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:

PowerShell
claude mcp add filesystem -- cmd /c npx -y @modelcontextprotocol/server-filesystem C:/Users/you/Documents

Cause 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:

Python
import os

API_KEY = os.environ["WEATHER_API_KEY"]  # KeyError -> process exits immediately

Fixed: 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:

Python
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:

Python
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:

Python
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:

Terminal
npx @modelcontextprotocol/inspector uv run --directory /Users/you/projects/notes-mcp server.py

You can pass environment variables with -e:

Terminal
npx @modelcontextprotocol/inspector -e WEATHER_API_KEY=test-key -- node /Users/you/projects/weather-mcp/dist/index.js

It 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 general mcp.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 list and the /mcp command inside a session. Running with --debug prints 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:

Terminal
tail -n 50 -f ~/Library/Logs/Claude/mcp-server-notes.log

A 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:

Terminal
{
  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.log

Then inspect stdout.log. Every line should be a JSON object starting with {"jsonrpc":"2.0". This snippet flags any line that isn't:

Terminal
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:

  1. Nothing writes to stdout except the MCP transport: no print, console.log, console.debug, npm script header, library banner or child process output.
  2. Logging is configured to stderr (logging with stream=sys.stderr, or console.error).
  3. command is an absolute path, or a name the client can definitely resolve.
  4. Script paths in args are absolute, or you use uv run --directory.
  5. File paths in code are resolved relative to the source file, not the working directory.
  6. The interpreter is the project's venv Python, not whatever python resolves to.
  7. Required API keys and any needed PATH entries are set in the config's env block.
  8. On Windows, npx is wrapped in cmd /c and backslashes in JSON are escaped.
  9. Heavy setup is lazy, so initialize returns quickly.
  10. The server works in the MCP Inspector and with a manual initialize request using the exact command from your config.
  11. 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.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch