Skip to main content

How to config MCP server with an env parameter in Cursor

Configuring Model Context Protocol (MCP) servers with environment parameters in Cursor allows you to securely pass sensitive information and customize server behavior. This guide provides detailed instructions on setting up and managing environment variables for your MCP servers.

Introduction to MCP Server Environment Configuration

Model Context Protocol (MCP) servers extend Cursor's AI capabilities by providing additional tools and resources. Environment parameters allow you to:

  • Pass API keys and authentication tokens securely
  • Configure server behavior without modifying code
  • Set up different environments (development, staging, production)
  • Customize server functionality based on deployment context

Why Use Environment Parameters?

Environment parameters offer several advantages:

  1. Security: Keep sensitive information out of your codebase
  2. Flexibility: Change configuration without modifying code
  3. Portability: Run the same server in different environments
  4. Separation of concerns: Keep configuration separate from implementation

Understanding MCP Server Configuration

Before adding environment parameters, it's important to understand the basic structure of MCP server configuration in Cursor.

MCP Configuration File Structure

MCP servers are configured in a JSON file with the following structure:

{
"mcpServers": {
"server-name": {
"command": "node",
"args": ["/path/to/server.js"],
"env": {
"KEY1": "value1",
"KEY2": "value2"
},
"disabled": false,
"autoApprove": ["tool1", "tool2"]
}
}
}

Key components:

  • server-name: A unique identifier for your MCP server
  • command: The command to run your server (e.g., node, python)
  • args: Arguments passed to the command
  • env: Environment variables passed to the server process
  • disabled: Whether the server is disabled
  • autoApprove: List of tools that don't require explicit approval

Step-by-Step Configuration Guide

1. Locate Your MCP Configuration File

The location of your MCP configuration file depends on your operating system:

Windows:

%APPDATA%\Code\User\globalStorage\tencent-cloud.coding-copilot\settings\Craft_mcp_settings.json

macOS:

~/Library/Application Support/Code/User/globalStorage/tencent-cloud.coding-copilot/settings/Craft_mcp_settings.json

Linux:

~/.config/Code/User/globalStorage/tencent-cloud.coding-copilot/settings/Craft_mcp_settings.json

2. Edit the Configuration File

  1. Open the configuration file in your preferred text editor
  2. If the file doesn't exist or is empty, create it with the following structure:
{
"mcpServers": {}
}
  1. Add or modify your server configuration:
{
"mcpServers": {
"my-server": {
"command": "node",
"args": ["/path/to/my-server.js"],
"env": {
"API_KEY": "your-api-key-here",
"DEBUG": "true",
"PORT": "3000"
},
"disabled": false
}
}
}

3. Add Environment Parameters

To add environment parameters to your MCP server:

  1. Identify the environment variables your server needs
  2. Add them to the env object in your server configuration
  3. Save the configuration file

Example with multiple environment variables:

"env": {
"OPENAI_API_KEY": "sk-abcdef123456",
"SERVER_PORT": "3000",
"LOG_LEVEL": "info",
"CACHE_ENABLED": "true",
"MAX_TOKENS": "4096",
"MODEL_NAME": "gpt-4",
"TIMEOUT_MS": "30000"
}

4. Using Environment Variables in Your MCP Server

In your MCP server code, you can access these environment variables:

JavaScript/Node.js:

const apiKey = process.env.API_KEY;
const debug = process.env.DEBUG === 'true';
const port = parseInt(process.env.PORT || '3000', 10);

console.log(`Starting server with API key ${apiKey} on port ${port}`);
if (debug) {
console.log('Debug mode enabled');
}

Python:

import os

api_key = os.environ.get('API_KEY')
debug = os.environ.get('DEBUG') == 'true'
port = int(os.environ.get('PORT', '3000'))

print(f"Starting server with API key {api_key} on port {port}")
if debug:
print("Debug mode enabled")

Advanced Configuration Techniques

Using Environment Files

For more complex configurations, you can use environment files:

  1. Create a .env file:
API_KEY=your-api-key-here
DEBUG=true
PORT=3000
  1. Update your MCP server configuration:
{
"mcpServers": {
"my-server": {
"command": "node",
"args": ["/path/to/my-server.js"],
"env": {
"ENV_FILE": "/path/to/.env"
}
}
}
}
  1. In your server code, load the environment file:

JavaScript/Node.js (using dotenv):

require('dotenv').config({ path: process.env.ENV_FILE });

// Now you can access the variables
const apiKey = process.env.API_KEY;

Python (using python-dotenv):

import os
from dotenv import load_dotenv

load_dotenv(os.environ.get('ENV_FILE'))

# Now you can access the variables
api_key = os.environ.get('API_KEY')

Environment Variable Expansion

You can reference other environment variables within your configuration:

"env": {
"BASE_URL": "https://api.example.com",
"API_ENDPOINT": "${BASE_URL}/v1/data",
"HOME_DIR": "${HOME}/projects"
}

Using System Environment Variables

You can reference system environment variables in your configuration:

"env": {
"USER_HOME": "${HOME}",
"SYSTEM_TEMP": "${TEMP}",
"CURRENT_USER": "${USER}"
}

Security Best Practices

When working with environment parameters, especially for sensitive information like API keys, follow these security best practices:

1. Never Commit Sensitive Information

  • Use .gitignore to exclude environment files
  • Don't commit configuration files with actual API keys
  • Use placeholder values in committed examples

2. Use Encryption for Sensitive Values

  • Consider encrypting sensitive environment variables
  • Use a secure key management system when possible

3. Limit Access to Configuration Files

  • Set appropriate file permissions
  • Restrict who can view and edit configuration files

4. Rotate Secrets Regularly

  • Change API keys and tokens periodically
  • Update your configuration files when secrets change

5. Validate Environment Variables

In your server code, validate environment variables before using them:

function validateEnv() {
const requiredVars = ['API_KEY', 'SERVER_PORT'];
const missing = requiredVars.filter(varName => !process.env[varName]);

if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
}

validateEnv();

Troubleshooting Common Issues

Environment Variables Not Available

Problem: Environment variables configured in MCP settings aren't available in your server.

Solutions:

  • Verify the configuration file syntax
  • Check that the server is being started correctly
  • Restart Cursor after making configuration changes
  • Check server logs for environment-related errors

Configuration File Not Found

Problem: Cursor can't find your MCP configuration file.

Solutions:

  • Verify the file path is correct for your operating system
  • Create the directory structure if it doesn't exist
  • Check file permissions
  • Restart Cursor after creating the file

Invalid JSON Format

Problem: Configuration file has JSON syntax errors.

Solutions:

  • Validate your JSON using a JSON validator
  • Check for missing commas, brackets, or quotes
  • Ensure all property names are in double quotes
  • Remove trailing commas

Server Crashes on Startup

Problem: MCP server crashes immediately after starting.

Solutions:

  • Check server logs for error messages
  • Verify all required environment variables are provided
  • Ensure environment variable values are in the correct format
  • Check for path issues in file references

Examples for Common Use Cases

1. OpenAI API Integration

{
"mcpServers": {
"openai-tools": {
"command": "node",
"args": ["/path/to/openai-server.js"],
"env": {
"OPENAI_API_KEY": "sk-your-key-here",
"MODEL": "gpt-4",
"MAX_TOKENS": "8192",
"TEMPERATURE": "0.7"
}
}
}
}

2. Database Connection

{
"mcpServers": {
"db-tools": {
"command": "python",
"args": ["/path/to/db-server.py"],
"env": {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_NAME": "mydb",
"DB_USER": "user",
"DB_PASSWORD": "password",
"CONNECTION_POOL_SIZE": "10"
}
}
}
}

3. Development vs. Production Settings

{
"mcpServers": {
"api-tools": {
"command": "node",
"args": ["/path/to/api-server.js"],
"env": {
"NODE_ENV": "development",
"API_URL": "http://localhost:8080/api",
"CACHE_ENABLED": "false",
"LOG_LEVEL": "debug"
}
}
}
}

Conclusion

Configuring MCP servers with environment parameters in Cursor provides a flexible, secure way to customize server behavior and manage sensitive information. By following the steps and best practices outlined in this guide, you can effectively set up and manage environment variables for your MCP servers.

Whether you're integrating with external APIs, connecting to databases, or simply customizing server behavior, environment parameters offer a clean separation between configuration and code, enhancing security and maintainability.

Additional Resources