Skip to main content
RapidDev - Software Development Agency
mcp-tutorial

How to fix MCP server crashing on startup

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.

What you'll learn

  • How to diagnose MCP servers that exit immediately after starting
  • The most common causes of startup crashes
  • How to run the server manually to see the real error
  • How to fix missing dependencies, version conflicts, and init errors
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate7 min read10-15 minAll MCP hosts and serversMarch 2026RapidDev Engineering Team
TL;DR

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

1

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.

typescript
1# 1. Find the command in your config
2# For example, if your config has:
3# "command": "node", "args": ["./dist/index.js"]
4
5# 2. Set environment variables
6export API_KEY="your-key-here"
7export DATABASE_URL="your-db-url"
8
9# 3. Run the exact command
10node ./dist/index.js
11
12# For npx servers:
13npx -y @modelcontextprotocol/server-github
14
15# For Python servers:
16uvx mcp-server-git --repository /path/to/repo
17
18# The error output will show exactly what went wrong

Expected result: The terminal shows the actual error that causes the server to crash, such as missing modules, syntax errors, or configuration issues.

2

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.

typescript
1# Error you might see:
2# "Error: Cannot find module '@modelcontextprotocol/sdk'"
3# "Error: Cannot find module 'zod'"
4# "MODULE_NOT_FOUND"
5
6# Fix for local servers:
7cd /path/to/your/mcp-server
8npm install
9npm run build # if TypeScript
10
11# Fix for npx servers (clear cache):
12npm cache clean --force
13npx -y @modelcontextprotocol/server-github # re-downloads
14
15# Fix for Python servers:
16uvx --reinstall mcp-server-git

Expected result: Dependencies are installed and the server starts without module errors.

3

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.

typescript
1# Check your Node.js version
2node --version
3# Must be v18.0.0 or later
4
5# Common version-related errors:
6# "SyntaxError: Unexpected token 'export'"
7# "ERR_UNKNOWN_FILE_EXTENSION: .mjs"
8# "SyntaxError: Cannot use import statement outside a module"
9
10# Upgrade Node.js:
11# macOS with Homebrew:
12brew install node@20
13
14# Using nvm:
15nvm install 20
16nvm use 20
17
18# Verify after upgrade:
19node --version

Expected result: Node.js 18+ is installed and the server no longer crashes with syntax or import errors.

4

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.

typescript
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"
5
6# Fix: add the variable to your host config
7{
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.

5

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.

typescript
1// Wrap server initialization in try-catch
2try {
3 // Validate environment
4 const apiKey = process.env.API_KEY;
5 if (!apiKey) throw new Error("API_KEY is required");
6
7 // Initialize external connections
8 const db = await connectToDatabase(process.env.DATABASE_URL);
9 console.error("Database connected");
10
11 // Create and start MCP server
12 const server = new McpServer({ name: "my-server", version: "1.0.0" });
13 registerTools(server, db);
14
15 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

src/robust-startup-server.ts
1import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3import { z } from "zod";
4
5console.error("=== MCP Server Starting ===");
6console.error(`Node.js: ${process.version}`);
7console.error(`Platform: ${process.platform}`);
8console.error(`CWD: ${process.cwd()}`);
9
10// Validate environment
11const requiredEnvVars = ["API_KEY"];
12const missingVars = requiredEnvVars.filter((v) => !process.env[v]);
13
14if (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 2
21 ));
22 process.exit(1);
23}
24
25console.error("Environment variables: OK");
26
27try {
28 const server = new McpServer({
29 name: "robust-server",
30 version: "1.0.0",
31 });
32
33 server.tool(
34 "hello",
35 "Say hello",
36 { name: z.string() },
37 async ({ name }) => ({
38 content: [{ type: "text", text: `Hello, ${name}!` }],
39 })
40 );
41
42 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}
50
51// Handle uncaught errors
52process.on("uncaughtException", (error) => {
53 console.error("Uncaught exception:", error.stack);
54 process.exit(1);
55});
56
57process.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.

ChatGPT Prompt

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.

MCP Prompt

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.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.