FastMCP defaults to stdio, which makes local Python servers easy to start and easy to misconfigure. The protocol owns stdout. Any library, print statement, or progress bar that writes to stdout can corrupt the stream.
Configure logging before the server starts
import logging
import os
import sys
logging.basicConfig(
level=logging.INFO,
stream=sys.stderr,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger = logging.getLogger("repo-tools")
def require_env(name: str) -> str:
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
Do this before importing libraries that might print a banner. Some SDKs and CLIs write to stdout during import or first-run setup; check the output with the server run manually.
Keep stdout clean
Avoid:
print(...)anywhere in the server path.- Progress bars that default to stdout.
- Web framework startup banners.
- Debugging output from HTTP libraries.
If a dependency insists on stdout, redirect it or run it in a subprocess whose stdout you capture. The safest pattern is to reserve stdout for the SDK transport and treat every other output stream as diagnostics.
Start the server explicitly
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("repo-tools")
@mcp.tool()
def read_config() -> str:
"""Read a non-secret configuration summary from an approved path."""
logger.info("read_config invoked")
return "configuration summary"
if __name__ == "__main__":
mcp.run(transport="stdio")
Using an explicit transport makes the deployment assumption visible. mcp.run() defaults to stdio, but code that will later support HTTP benefits from saying which mode is intended.
Handle the environment deliberately
A stdio server inherits the client process environment plus any env configured for it. Read secrets from environment variables and validate them at startup. Do not fall back to a hard-coded development token: a missing env var should fail loudly.
Clients format env differently:
- Claude Code
.mcp.jsonsupports${VAR}expansion. - Codex stdio config uses literal
envvalues by default. - Cursor and Windsurf document
${env:VAR}interpolation. - VS Code uses
${input:id}prompts.
Do not copy an environment reference from one client to another without checking the syntax. The client center documents each format, and the Config Generator emits the right form.
Lifecycle and shutdown
A stdio server should stay alive until the client closes the connection. Avoid starting threads that keep the interpreter alive after the transport closes. If you open database pools or HTTP clients, close them in a shutdown hook.
import atexit
@atexit.register
def close_resources() -> None:
logger.info("shutting down")
atexit is a backstop, not a guarantee for abrupt termination. Handle SIGTERM if the process is managed by a supervisor or container. For a local stdio server, the client owns the process lifetime; make shutdown idempotent.
Packaging for a client
A reproducible command looks like:
{
"mcpServers": {
"repo-tools": {
"command": "uv",
"args": ["run", "--directory", "/absolute/path/to/repo-tools", "server.py"],
"env": { "REPO_ROOT": "/absolute/path/to/repository" }
}
}
}
Use absolute paths. If the client cannot find uv, use its absolute path. For a locked installation without network access, install the project into a virtual environment and point command at that environment’s Python executable.
Diagnose the common failures
- Server missing or ENOENT: the command is not on the client’s PATH. Test it from the client’s environment.
- Server exits immediately: run it manually and read stderr; check required environment variables.
- Protocol parse errors: something wrote non-JSON to stdout.
- Permission denied: the client runs as a different user or lacks access to the configured path.
- Hangs after startup: the server is waiting for input correctly, or a tool call is blocked on a dependency.
Use the unexpected exit guide for process crashes and the EACCES guide for filesystem access failures.
Verify before shipping
- The process starts manually and waits.
- MCP Inspector can list and invoke every tool.
- A missing environment variable produces a clear stderr error.
- Closing the client terminates the process.
- No
print()remains in the server path. - A failed tool call leaves the server connected.
For remote deployment, move to Python Streamable HTTP. For packaging and release checks, use the Python production checklist.
Sources
Sources were checked on Oct 23, 2026. Versions and client behavior can change; confirm the current documentation before relying on a configuration.