When an MCP server crashes immediately on startup, the host shows it as disconnected with no helpful error. The fix is to run the server command manually in your terminal to see the actual error output. Common causes are missing npm dependencies (run npm install), wrong Node.js version, unhandled errors in initialization code, and missing required environment variables. Always test the server in your terminal before configuring it in a host.
Fixing MCP Servers That Crash on Startup
An MCP server that crashes on startup is frustrating because the host often shows only a generic 'disconnected' status with no details. The server starts, encounters an error, and exits before the host can establish a connection. The key insight is to run the server command outside the host, directly in your terminal, where you can see the full error output.
Prerequisites
- An MCP server that shows as disconnected immediately after the host starts
- Terminal access on your machine
- The server's configuration from your MCP host config file
Step-by-step guide
Run the server command manually in your terminal
Run the server command manually in your terminal
Copy the exact command and args from your MCP host configuration and run them in your terminal. Include any environment variables from the env block by exporting them first. The terminal will show the full error output that the host does not display. This is the single most important debugging step — it reveals the actual cause in almost every case.
1# 1. Find the command in your config2# For example, if your config has:3# "command": "node", "args": ["./dist/index.js"]45# 2. Set environment variables6export API_KEY="your-key-here"7export DATABASE_URL="your-db-url"89# 3. Run the exact command10node ./dist/index.js1112# For npx servers:13npx -y @modelcontextprotocol/server-github1415# For Python servers:16uvx mcp-server-git --repository /path/to/repo1718# The error output will show exactly what went wrongExpected result: The terminal shows the actual error that causes the server to crash, such as missing modules, syntax errors, or configuration issues.
Fix missing npm dependencies
Fix missing npm dependencies
The most common startup crash is a missing module error. This happens when the server's node_modules directory is incomplete or was not installed. Navigate to the server's directory and run npm install. For npx-based servers, clear the npx cache and try again. The error message will say something like 'Cannot find module' followed by the package name.
1# Error you might see:2# "Error: Cannot find module '@modelcontextprotocol/sdk'"3# "Error: Cannot find module 'zod'"4# "MODULE_NOT_FOUND"56# Fix for local servers:7cd /path/to/your/mcp-server8npm install9npm run build # if TypeScript1011# Fix for npx servers (clear cache):12npm cache clean --force13npx -y @modelcontextprotocol/server-github # re-downloads1415# Fix for Python servers:16uvx --reinstall mcp-server-gitExpected result: Dependencies are installed and the server starts without module errors.
Check Node.js version compatibility
Check Node.js version compatibility
MCP SDK requires Node.js 18 or later. If you are running an older version, the server will crash with syntax errors (unexpected token for modern JavaScript features) or import errors (ERR_UNKNOWN_FILE_EXTENSION for .mjs files). Check your Node.js version and upgrade if needed.
1# Check your Node.js version2node --version3# Must be v18.0.0 or later45# Common version-related errors:6# "SyntaxError: Unexpected token 'export'"7# "ERR_UNKNOWN_FILE_EXTENSION: .mjs"8# "SyntaxError: Cannot use import statement outside a module"910# Upgrade Node.js:11# macOS with Homebrew:12brew install node@201314# Using nvm:15nvm install 2016nvm use 201718# Verify after upgrade:19node --versionExpected result: Node.js 18+ is installed and the server no longer crashes with syntax or import errors.
Fix missing environment variables
Fix missing environment variables
Many servers validate required environment variables at startup and exit with an error if they are missing. Check the server's documentation or README for required variables. The error message typically names the missing variable. Add it to the env block in your MCP host configuration.
1# Error messages indicating missing env vars:2# "FATAL: API_KEY environment variable is required"3# "Error: Missing required configuration: GITHUB_PERSONAL_ACCESS_TOKEN"4# "Environment variable DATABASE_URL is not set"56# Fix: add the variable to your host config7{8 "mcpServers": {9 "my-server": {10 "command": "node",11 "args": ["./dist/index.js"],12 "env": {13 "API_KEY": "your-key-here"14 }15 }16 }17}Expected result: The server receives all required environment variables and starts successfully.
Handle unhandled errors in server initialization
Handle unhandled errors in server initialization
If your own server crashes during initialization (before the MCP connection is established), the error may not be caught by the MCP SDK's error handling. Wrap your initialization code in a try-catch and log the error to stderr. Common init-time failures include database connections, file system access, and API validation. If your server has complex initialization requirements and you need help designing a robust startup sequence, the RapidDev team can assist with architecture decisions.
1// Wrap server initialization in try-catch2try {3 // Validate environment4 const apiKey = process.env.API_KEY;5 if (!apiKey) throw new Error("API_KEY is required");67 // Initialize external connections8 const db = await connectToDatabase(process.env.DATABASE_URL);9 console.error("Database connected");1011 // Create and start MCP server12 const server = new McpServer({ name: "my-server", version: "1.0.0" });13 registerTools(server, db);1415 const transport = new StdioServerTransport();16 await server.connect(transport);17 console.error("MCP server ready");18} catch (error) {19 console.error("FATAL: Server failed to start:");20 console.error(error instanceof Error ? error.stack : String(error));21 process.exit(1);22}Expected result: Initialization errors are caught, logged with full details, and the server exits cleanly with a non-zero code.
Complete working example
1import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";2import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";3import { z } from "zod";45console.error("=== MCP Server Starting ===");6console.error(`Node.js: ${process.version}`);7console.error(`Platform: ${process.platform}`);8console.error(`CWD: ${process.cwd()}`);910// Validate environment11const requiredEnvVars = ["API_KEY"];12const missingVars = requiredEnvVars.filter((v) => !process.env[v]);1314if (missingVars.length > 0) {15 console.error(`FATAL: Missing environment variables: ${missingVars.join(", ")}`);16 console.error("Add them to your MCP host config:");17 console.error(JSON.stringify(18 { env: Object.fromEntries(missingVars.map((v) => [v, "your-value"])) },19 null,20 221 ));22 process.exit(1);23}2425console.error("Environment variables: OK");2627try {28 const server = new McpServer({29 name: "robust-server",30 version: "1.0.0",31 });3233 server.tool(34 "hello",35 "Say hello",36 { name: z.string() },37 async ({ name }) => ({38 content: [{ type: "text", text: `Hello, ${name}!` }],39 })40 );4142 const transport = new StdioServerTransport();43 await server.connect(transport);44 console.error("=== MCP Server Ready ===");45} catch (error) {46 console.error("FATAL: Server initialization failed:");47 console.error(error instanceof Error ? error.stack : String(error));48 process.exit(1);49}5051// Handle uncaught errors52process.on("uncaughtException", (error) => {53 console.error("Uncaught exception:", error.stack);54 process.exit(1);55});5657process.on("unhandledRejection", (reason) => {58 console.error("Unhandled rejection:", reason);59 process.exit(1);60});Common mistakes when fixing MCP server crashing on startup
Why it's a problem: Only looking at the host's error message instead of running the server manually
How to avoid: The host shows generic errors. Run the exact command from your config in your terminal to see the real error output.
Why it's a problem: Forgetting to run npm install or npm run build after cloning a server
How to avoid: Always run npm install to install dependencies and npm run build (if TypeScript) before trying to start the server.
Why it's a problem: Using an outdated Node.js version
How to avoid: MCP SDK requires Node.js 18+. Run node --version and upgrade if needed.
Why it's a problem: Not wrapping initialization code in try-catch
How to avoid: Errors during server setup (before MCP connection) need explicit error handling. Wrap everything in try-catch and log to stderr.
Best practices
- Always test new servers by running them manually in the terminal first
- Add startup logging that reports Node.js version, platform, and environment variable status
- Wrap all initialization code in try-catch with detailed error logging
- Add uncaughtException and unhandledRejection handlers for safety
- Validate all required environment variables at startup before creating the MCP server
- Include the server version in startup logs so you know which version is running
- Run npm install and npm run build after every git pull for locally developed servers
Still stuck?
Copy one of these prompts to get a personalized, step-by-step explanation.
My MCP server shows as disconnected in [Claude Desktop / Cursor] immediately after starting. When I run [command] in my terminal, I see this error: [paste error]. Help me fix the startup crash.
Add robust startup error handling to my MCP server. I need environment variable validation, dependency checks, and a try-catch wrapper around initialization. Show me the complete entry point code.
Frequently asked questions
How can I tell if the server crashed vs. just failed to connect?
Check the MCP host logs. A crash shows the server process exiting (often with a non-zero exit code). A connection failure shows timeout or connection refused errors while the server may still be running.
My server works when I run it manually but crashes from the host. Why?
The host may set different working directory, PATH, or environment. Check that your server does not rely on relative paths (use absolute paths), shell-specific PATH entries, or environment variables set in your shell profile.
Can I attach a debugger to an MCP server started by the host?
Not directly, because the host manages the process lifecycle. Instead, add the --inspect flag to your Node.js command in the config args, then connect Chrome DevTools. Note that breakpoints will pause the entire server.
The server crashes after running for a few minutes, not immediately. What is different?
Delayed crashes are usually caused by memory leaks, unhandled promise rejections, or connection timeouts to external services. Add unhandledRejection and uncaughtException handlers, and check for memory growth over time.
How do I rollback to a previous working version of my server?
If using git, check out the last working commit. If using npx, specify the previous version: npx -y @scope/server@previous-version. If the server is locally built, restore from your build artifacts or git history.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation