MCP error -32000: Connection closed means the MCP client lost its connection to the server before it got an answer. With a local stdio server, that almost always means the server process exited. The client started it, sent its first request, and the process died: a Python import failed, a required environment variable was missing, a relative path pointed at nothing, or the script never started the server at all. The error itself carries no cause. The cause is in the server's stderr, so the fix starts with reading it.
This post shows where the code comes from, reproduces the common causes and their exact stderr, and gives a fix for each. Every case was run on Linux with Node.js 22 and the official MCP TypeScript SDK client (version 1.32.2), launching small Python servers built with the official Python SDK (version 2.3.0).
Where -32000 comes from
In the TypeScript SDK, -32000 is ErrorCode.ConnectionClosed, and -32001 is RequestTimeout. When the transport reports that it closed, the SDK's protocol layer fails every request still waiting for a response with McpError(ErrorCode.ConnectionClosed, 'Connection closed'). The stdio client transport reports a close when the child process emits Node's close event, which happens when the process exits.
So the message is a symptom, not a diagnosis. It says "the server went away while I was waiting." The Python SDK uses the same code: its dispatcher fails pending requests with CONNECTION_CLOSED and the message Connection closed.
A -32001: Request timed out is different. There the server is still running but did not answer in time. If you see that one, the process started and something inside it is slow or stuck.
Reproducing the common causes
This script connects to a stdio server with the TypeScript SDK client, lists its tools and calls the first one. It prints whatever the server writes to stderr, so the real error shows up next to the client's error:
// probe.mjs: npm install @modelcontextprotocol/sdk
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const [command, ...args] = process.argv.slice(2);
const transport = new StdioClientTransport({ command, args, stderr: "pipe" });
transport.stderr?.on("data", (d) => process.stderr.write("server stderr: " + d));
transport.onerror = (e) => console.log("transport error:", e.message);
const client = new Client({ name: "probe", version: "1.0.0" });
try {
await client.connect(transport);
const { tools } = await client.listTools();
console.log("connected,", tools.length, "tools");
const res = await client.callTool({ name: tools[0].name, arguments: { a: 2, b: 3 } });
console.log("call result:", JSON.stringify(res.content));
} catch (e) {
console.log("failed:", e.message);
} finally {
await client.close().catch(() => {});
}
The working server is the smallest one the Python SDK allows:
# good.py
from mcp.server import MCPServer
mcp = MCPServer("Demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
if __name__ == "__main__":
mcp.run()
Run against it, the probe prints connected, 1 tools and call result: [{"type":"text","text":"5"}]. Each case below changes one thing.
1. An import fails
Add import httpx_extras (a package that isn't installed) to the top of the server. The output, trimmed:
server stderr: Traceback (most recent call last):
File ".../servers/crash_import.py", line 1, in <module>
import httpx_extras # not installed
ModuleNotFoundError: No module named 'httpx_extras'
failed: MCP error -32000: Connection closed
The same thing happens when the command points at the wrong Python. Running the working good.py with a fresh virtual environment that doesn't have the SDK gave ModuleNotFoundError: No module named 'mcp' and the same -32000. The server code is fine; the interpreter is not the one you installed into.
Fix: use the absolute path to the interpreter of the environment that has your dependencies, for example /path/to/project/.venv/bin/python, or let uv pick it (case 4).
2. A required environment variable is missing
A server that reads its API key at import time:
import os
from mcp.server import MCPServer
API_KEY = os.environ["WEATHER_API_KEY"]
mcp = MCPServer("Demo")
The last lines of the output:
server stderr: KeyError: 'WEATHER_API_KEY'
failed: MCP error -32000: Connection closed
The surprise is that exporting the variable in your shell does not help. Running the probe with WEATHER_API_KEY=x set in its own environment gave the same KeyError. The TypeScript SDK's stdio client does not pass your whole environment to the server. It copies an allowlist, DEFAULT_INHERITED_ENV_VARS (on macOS and Linux: HOME, LOGNAME, PATH, SHELL, TERM and USER), then merges the transport's env option on top. The MCP debugging guide says the same about hosts in general: stdio servers "inherit only a limited subset of environment variables automatically."
Fix: pass the variable in the server's own env setting. In a host config that is an env block; in code, the transport's env option. With env: { WEATHER_API_KEY: "test" } on the transport, the same server connected. In Claude Code, --env does this:
claude mcp add --env WEATHER_API_KEY=YOUR_KEY --transport stdio weather \
-- /path/to/project/.venv/bin/python /path/to/project/server.py
The Claude Code docs note that everything after -- goes to the server untouched, and that at least one other option, such as --transport stdio, must sit between --env and the server name.
3. A relative path
Starting the probe from / with servers/good.py as the argument:
server stderr: .../venv/bin/python: can't open file '//servers/good.py': [Errno 2] No such file or directory
failed: MCP error -32000: Connection closed
The path resolved against the client's working directory, not the folder you had in mind. The MCP debugging guide warns that the working directory for a server launched from a client's config "may be undefined (like / on macOS)" and says to always use absolute paths in your configuration and .env files.
Fix: absolute paths for the script and for every file the server opens. Inside the server, build paths from Path(__file__).parent rather than the current directory.
4. uv run from the wrong directory
uv run server.py started from /:
server stderr: error: Failed to spawn: `server.py`
Caused by: No such file or directory (os error 2)
failed: MCP error -32000: Connection closed
Fix: tell uv where the project is. uv's CLI reference says --directory will "change to the given directory prior to running the command," with relative paths resolved from it. uv run --directory /path/to/project server.py, started from /, connected and returned 5. Note that --project is not a drop-in replacement: it finds the project in that directory but resolves other relative paths, like server.py, from the current one. A --directory that doesn't exist fails too, with error: No such file or directory (os error 2) on stderr.
5. The server never starts
Delete the if __name__ == "__main__": mcp.run() block and the file defines a server but never runs it. Python imports the module, reaches the end and exits with no error:
failed: MCP error -32000: Connection closed
This is the one case with nothing on stderr, which makes it the most confusing. If stderr is empty and the process exits, check that the entry point actually calls mcp.run(), and that the host launches the file you think it does.
6. Printing to stdout
The stdio transport carries the protocol on stdout. The specification is strict: the server "MUST NOT write anything to its stdout that is not a valid MCP message." Messages are newline-delimited JSON-RPC, so a stray line is a line the client can't parse.
In this test a stray print() did not close the connection. With print("Demo server starting", flush=True) before mcp.run(), the TypeScript client reported a transport error and carried on:
transport error: Unexpected token 'D', "Demo server starting" is not valid JSON
connected, 1 tools
call result: [{"type":"text","text":"5"}]
The SDK's stdio client catches the parse error, passes it to onerror and keeps reading. Other hosts may handle a bad line differently, and a print that lands in the middle of a message would break that message, so treat stdout as off limits either way.
One detail from the Python SDK: a print(..., flush=True) inside a tool, called while the server was running, showed up on stderr, not stdout. The SDK's stdio transport (mcp/server/stdio.py in version 2.3.0) moves the protocol stream to a private file descriptor while it runs, using os.dup2. A print before mcp.run() happens before that, which is why the startup line above reached stdout. Without flush=True, both lines sat in Python's output buffer and reached stdout only when the process exited, where the client logged a parse error for each. Don't rely on any of this.
Fix: log to stderr. In Python, print(..., file=sys.stderr) or the logging module, whose StreamHandler uses sys.stderr when no stream is given. In Node, console.error, which the Node docs say prints to stderr, not console.log, which prints to stdout. With the prints moved to stderr, the same server connected with no transport errors. The MCP debugging guide gives the same advice: local servers "should not log messages to stdout."
A debugging routine
- Find the server's stderr. Claude Desktop writes it to
mcp-server-NAME.login its log folder (~/Library/Logs/Claudeon macOS,%APPDATA%\Claude\logson Windows,~/.config/Claude/logson Linux). In your own client, set the transport'sstderrto"pipe"and print it, as the probe does. - Run the exact command by hand from a different directory, such as
cd / && /path/to/.venv/bin/python /path/to/server.py. A working stdio server waits for input; Ctrl+C stops it. A traceback here is your answer. - Strip the environment.
env -i HOME=$HOME PATH=/usr/bin:/bin /path/to/.venv/bin/python /path/to/server.pyshows what the server does without your shell's variables, which is close to what a host gives it. - Open it in the MCP Inspector, which the debugging guide calls "your first stop":
npx @modelcontextprotocol/inspector /path/to/.venv/bin/python /path/to/server.py. Its--climode with--method tools/listlists the tools and exits, which is handy in CI. - Restart the host after config changes. The guide says Claude Desktop must be fully quit and reopened; closing the window is not enough. In Claude Code,
claude mcp listshows each server's status and/mcpchecks it from inside a session; the text afterFailed to connectnames the cause, as covered in Claude Code MCP Failed to Connect.
If the failure is spawn ... ENOENT rather than -32000, the host could not find the command at all. That is covered in MCP server not showing up in Claude Desktop, including the case where npx is found but node isn't, which also ends in Connection closed.
Make the server fail loudly
Most of these failures are easier to read if the server checks its own setup first:
import os
import sys
from mcp.server import MCPServer
API_KEY = os.environ.get("WEATHER_API_KEY")
if not API_KEY:
sys.exit("weather server: WEATHER_API_KEY is not set; add it to the server's env config")
mcp = MCPServer("Weather")
sys.exit with a string prints it to stderr and exits with status 1, so the host log shows one clear line instead of a traceback. The client still reports -32000, but the log now says why. For the full structure of a server, see Build an MCP server in Python.
A crash after startup also produces -32000, mid-session instead of at connect. The 2026-07-28 stdio spec says that if the server exits unexpectedly, the client "SHOULD restart it," and in-flight requests "are simply lost." If your agent calls MCP tools, treat a closed connection like any other failed tool call and decide whether it is safe to retry; agent tool retries covers which calls can be repeated.
Checklist
- Read the server's stderr first;
-32000only says the process went away. - Use the absolute path to the interpreter that has your dependencies.
- Pass API keys and settings in the server's
envconfig, not your shell. - Use absolute paths for scripts and files, or
uv run --directory. - Make sure the entry point calls
mcp.run(). - Keep stdout for protocol messages; log to stderr.
- Run the exact command by hand from
/and with a stripped environment. - Restart the host after every config change.
FAQ
What does MCP error -32000 Connection closed mean?
The client's connection to the server closed while a request was waiting for a response. In the TypeScript SDK, -32000 is ErrorCode.ConnectionClosed. For a stdio server it nearly always means the server process exited.
Why does my MCP server work in the terminal but not in the client?
The client starts it with a different working directory and a reduced environment. Relative paths, variables you exported in your shell and the Python on your shell's PATH may all be different. Use absolute paths and an env block.
Can print() break an MCP stdio server?
The spec forbids anything but MCP messages on stdout. In our test, the TypeScript SDK client logged a parse error for a stray line and kept going, but other clients may not, and a print in the middle of a message corrupts it. Log to stderr.
What is the difference between -32000 and -32001?
-32000 means the connection closed. -32001 means a request timed out while the connection stayed open. A timeout points at a slow or stuck server, not one that exited.
Where do I find the real error?
In the server's stderr. Claude Desktop saves it to mcp-server-NAME.log; in your own client, pipe the transport's stderr. Running the same command by hand also shows it.
Sources
- Model Context Protocol, stdio transport (specification 2026-07-28: stdout rules, stderr logging, shutdown, unexpected termination)
- Model Context Protocol, Debugging (docs: stdout warning, working directory, inherited environment, Claude Desktop logs and restarts)
- Model Context Protocol, Connect to local MCP servers (docs: Claude Desktop log folders,
mcp-server-SERVERNAME.log) - Model Context Protocol, MCP Inspector (docs: launching against a stdio server, CLI mode)
- MCP TypeScript SDK, @modelcontextprotocol/sdk (package source, version 1.32.2:
types.jsErrorCode,shared/protocol.js,client/stdio.js) - MCP Python SDK, mcp on PyPI (package source, version 2.3.0:
mcp/server/stdio.py,mcp/shared/jsonrpc_dispatcher.py) - Anthropic, Connect Claude Code to tools via MCP (docs:
claude mcp add,--env, the--separator,claude mcp list,/mcp) - uv, CLI reference (docs:
--directoryand--project) - Python, logging.handlers (documentation: StreamHandler defaults to sys.stderr)
- Node.js, Console (documentation: console.log to stdout, console.error to stderr)