# How to configure environment variables for MCP servers

- Tool: MCP
- Difficulty: Beginner
- Time required: 5-10 min
- Compatibility: All MCP hosts (Claude Desktop, Cursor, Windsurf, etc.)
- Last updated: March 2026

## TL;DR

MCP server environment variables are configured in your host's JSON config file using the env block inside each server definition. Claude Desktop uses claude_desktop_config.json, Cursor uses .cursor/mcp.json, and each platform has slightly different syntax. Environment variables are the correct way to pass API keys and secrets to MCP servers — never hardcode them in your server code.

## Configuring Environment Variables for MCP Servers

Most MCP servers need API keys, database URLs, or other configuration values to work. The MCP specification lets you set environment variables in your host's config file, and they are automatically injected into the server process when it starts. This tutorial covers the configuration syntax for every major MCP host and shows you how to read these values in both TypeScript and Python servers.

## Before you start

- An MCP host installed (Claude Desktop, Cursor, or similar)
- An MCP server you want to configure
- The API key or secret you need to pass to the server

## Step-by-step guide

### 1. Locate your MCP host configuration file

Each MCP host stores its server configuration in a specific JSON file. Claude Desktop on macOS uses ~/Library/Application Support/Claude/claude_desktop_config.json. On Windows, it is %APPDATA%\Claude\claude_desktop_config.json. Cursor uses .cursor/mcp.json in your project directory for project-scoped servers, or ~/.cursor/mcp.json for global servers. Open this file in any text editor.

```
# Claude Desktop config location
# macOS:
~/Library/Application Support/Claude/claude_desktop_config.json

# Windows:
%APPDATA%\Claude\claude_desktop_config.json

# Cursor config location
# Project-scoped:
.cursor/mcp.json

# Global:
~/.cursor/mcp.json
```

**Expected result:** You have found and opened your host's configuration file.

### 2. Add environment variables to your server config

Inside your server definition, add an env object with key-value pairs for each environment variable. The keys become environment variable names and the values are their contents. These variables are set in the server process environment when the host starts the server. This is the correct and secure way to pass API keys — never put them directly in your server's source code.

```
{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["./dist/index.js"],
      "env": {
        "API_KEY": "sk-your-api-key-here",
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb",
        "LOG_LEVEL": "debug"
      }
    }
  }
}
```

**Expected result:** Your config file now includes an env block with the required API keys and configuration values.

### 3. Access environment variables in your server code

In your MCP server, read environment variables using the standard approach for your language. In TypeScript/Node.js, use process.env.VARIABLE_NAME. In Python, use os.environ["VARIABLE_NAME"] or os.environ.get("VARIABLE_NAME", "default"). Always validate that required variables are present at startup and fail with a clear error message if they are missing.

```
// TypeScript — reading env vars in your MCP server
const apiKey = process.env.API_KEY;
if (!apiKey) {
  console.error("ERROR: API_KEY environment variable is not set");
  console.error("Add it to your MCP host config under the env block");
  process.exit(1);
}

// Python — reading env vars
import os
import sys

api_key = os.environ.get("API_KEY")
if not api_key:
    print("ERROR: API_KEY environment variable is not set", file=sys.stderr)
    sys.exit(1)
```

**Expected result:** Your server reads the environment variables at startup and fails clearly if they are missing.

### 4. Configure environment variables for npx-based servers

Many community MCP servers are distributed as npm packages and run via npx. You configure environment variables the same way — add an env block alongside the command and args fields. The environment variables are passed to the npx child process which forwards them to the server. This is how you configure servers you did not write, like @modelcontextprotocol/server-github or @modelcontextprotocol/server-slack.

```
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_your_token_here"
      }
    },
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": {
        "SLACK_BOT_TOKEN": "xoxb-your-token",
        "SLACK_TEAM_ID": "T01234567"
      }
    }
  }
}
```

**Expected result:** Third-party MCP servers receive their required API keys and tokens through environment variables.

### 5. Restart your MCP host to apply changes

After editing the configuration file, you must restart your MCP host for the changes to take effect. Claude Desktop requires a full application restart — quit and reopen it. Cursor typically picks up changes when you reload the window (Cmd+Shift+P then Reload Window), though a full restart is more reliable. Verify the connection by checking that the server's tools appear in your host. If you manage multiple MCP servers with complex configurations and need help streamlining the setup, the RapidDev team can help architect a clean configuration.

**Expected result:** Your MCP host restarts, connects to the server, and the server has access to all configured environment variables.

## Complete code example

File: `claude_desktop_config.json`

```json
{
  "mcpServers": {
    "my-custom-server": {
      "command": "node",
      "args": ["./mcp-servers/my-server/dist/index.js"],
      "env": {
        "API_KEY": "sk-your-api-key-here",
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb",
        "LOG_LEVEL": "info",
        "MAX_RESULTS": "50"
      }
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_your_token_here"
      }
    },
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/yourname/projects",
        "/Users/yourname/documents"
      ]
    }
  }
}
```

## Common mistakes

- **Hardcoding API keys in server source code instead of using env** — undefined Fix: Always use the env block in your host config to pass secrets. This keeps them out of your codebase and version control.
- **Forgetting to restart the MCP host after changing config** — undefined Fix: Environment variables are only read when the server starts. Restart Claude Desktop or reload Cursor after any config changes.
- **Using the wrong environment variable name** — undefined Fix: Check the MCP server's documentation for the exact variable names it expects. Names are case-sensitive — GITHUB_TOKEN is different from github_token.
- **Putting env vars in a .env file instead of the host config** — undefined Fix: MCP hosts do not read .env files. Environment variables must be in the env block of your host's JSON configuration.

## Best practices

- Always use the env block in your MCP host config for API keys and secrets
- Validate required environment variables at server startup with clear error messages
- Never commit configuration files containing real API keys to version control
- Use descriptive environment variable names that match the server's documentation
- Keep a template config file with placeholder values for team members to copy
- Set LOG_LEVEL as an environment variable to control verbosity without code changes

## Frequently asked questions

### Can I reference system environment variables in the MCP config?

No, the env block in MCP host configs uses literal string values. You cannot reference $HOME or %PATH%. If you need system variables, consider wrapping your server in a shell script that reads them.

### Are environment variables encrypted in the config file?

No, they are stored in plain text in the JSON config file. Protect the file with appropriate file system permissions and never commit it to version control with real secrets.

### Can I use .env files with MCP servers?

Not directly through the host config. However, your server code can use a library like dotenv to load .env files. The env block in the host config takes precedence over .env file values for the same variable name.

### Do env variables persist across server restarts?

Yes, the env block is read from the config file every time the host starts the server. As long as the config file has the values, they will be available.

### How do I pass environment variables to a Python MCP server?

The same way — use the env block in your host config. Python servers access them with os.environ.get('VARIABLE_NAME'). The host sets them in the process environment before starting the server, regardless of the language.

### What happens if I set an env variable that the server does not use?

Nothing — unused environment variables are simply ignored. They exist in the process environment but have no effect unless the server code reads them.

---

Source: https://www.rapidevelopers.com/mcp-tutorial/how-to-configure-mcp-server-environment-variables
© RapidDev — https://www.rapidevelopers.com/mcp-tutorial/how-to-configure-mcp-server-environment-variables
