# How to fix MCP server crashing on startup

- Tool: MCP
- Difficulty: Intermediate
- Time required: 10-15 min
- Compatibility: All MCP hosts and servers
- Last updated: March 2026

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

## Before you start

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

```
# 1. Find the command in your config
# For example, if your config has:
# "command": "node", "args": ["./dist/index.js"]

# 2. Set environment variables
export API_KEY="your-key-here"
export DATABASE_URL="your-db-url"

# 3. Run the exact command
node ./dist/index.js

# For npx servers:
npx -y @modelcontextprotocol/server-github

# For Python servers:
uvx mcp-server-git --repository /path/to/repo

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

```
# Error you might see:
# "Error: Cannot find module '@modelcontextprotocol/sdk'"
# "Error: Cannot find module 'zod'"
# "MODULE_NOT_FOUND"

# Fix for local servers:
cd /path/to/your/mcp-server
npm install
npm run build  # if TypeScript

# Fix for npx servers (clear cache):
npm cache clean --force
npx -y @modelcontextprotocol/server-github  # re-downloads

# Fix for Python servers:
uvx --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.

```
# Check your Node.js version
node --version
# Must be v18.0.0 or later

# Common version-related errors:
# "SyntaxError: Unexpected token 'export'"
# "ERR_UNKNOWN_FILE_EXTENSION: .mjs"
# "SyntaxError: Cannot use import statement outside a module"

# Upgrade Node.js:
# macOS with Homebrew:
brew install node@20

# Using nvm:
nvm install 20
nvm use 20

# Verify after upgrade:
node --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.

```
# Error messages indicating missing env vars:
# "FATAL: API_KEY environment variable is required"
# "Error: Missing required configuration: GITHUB_PERSONAL_ACCESS_TOKEN"
# "Environment variable DATABASE_URL is not set"

# Fix: add the variable to your host config
{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["./dist/index.js"],
      "env": {
        "API_KEY": "your-key-here"
      }
    }
  }
}
```

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

```
// Wrap server initialization in try-catch
try {
  // Validate environment
  const apiKey = process.env.API_KEY;
  if (!apiKey) throw new Error("API_KEY is required");

  // Initialize external connections
  const db = await connectToDatabase(process.env.DATABASE_URL);
  console.error("Database connected");

  // Create and start MCP server
  const server = new McpServer({ name: "my-server", version: "1.0.0" });
  registerTools(server, db);

  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("MCP server ready");
} catch (error) {
  console.error("FATAL: Server failed to start:");
  console.error(error instanceof Error ? error.stack : String(error));
  process.exit(1);
}
```

**Expected result:** Initialization errors are caught, logged with full details, and the server exits cleanly with a non-zero code.

## Complete code example

File: `src/robust-startup-server.ts`

```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

console.error("=== MCP Server Starting ===");
console.error(`Node.js: ${process.version}`);
console.error(`Platform: ${process.platform}`);
console.error(`CWD: ${process.cwd()}`);

// Validate environment
const requiredEnvVars = ["API_KEY"];
const missingVars = requiredEnvVars.filter((v) => !process.env[v]);

if (missingVars.length > 0) {
  console.error(`FATAL: Missing environment variables: ${missingVars.join(", ")}`);
  console.error("Add them to your MCP host config:");
  console.error(JSON.stringify(
    { env: Object.fromEntries(missingVars.map((v) => [v, "your-value"])) },
    null,
    2
  ));
  process.exit(1);
}

console.error("Environment variables: OK");

try {
  const server = new McpServer({
    name: "robust-server",
    version: "1.0.0",
  });

  server.tool(
    "hello",
    "Say hello",
    { name: z.string() },
    async ({ name }) => ({
      content: [{ type: "text", text: `Hello, ${name}!` }],
    })
  );

  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("=== MCP Server Ready ===");
} catch (error) {
  console.error("FATAL: Server initialization failed:");
  console.error(error instanceof Error ? error.stack : String(error));
  process.exit(1);
}

// Handle uncaught errors
process.on("uncaughtException", (error) => {
  console.error("Uncaught exception:", error.stack);
  process.exit(1);
});

process.on("unhandledRejection", (reason) => {
  console.error("Unhandled rejection:", reason);
  process.exit(1);
});
```

## Common mistakes

- **Only looking at the host's error message instead of running the server manually** — undefined Fix: The host shows generic errors. Run the exact command from your config in your terminal to see the real error output.
- **Forgetting to run npm install or npm run build after cloning a server** — undefined Fix: Always run npm install to install dependencies and npm run build (if TypeScript) before trying to start the server.
- **Using an outdated Node.js version** — undefined Fix: MCP SDK requires Node.js 18+. Run node --version and upgrade if needed.
- **Not wrapping initialization code in try-catch** — undefined Fix: 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

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

---

Source: https://www.rapidevelopers.com/mcp-tutorial/how-to-fix-mcp-server-crashing-on-startup
© RapidDev — https://www.rapidevelopers.com/mcp-tutorial/how-to-fix-mcp-server-crashing-on-startup
