|
| 1 | +# Environment Variables |
| 2 | + |
| 3 | +MCP servers commonly need access to API keys, database URLs, and other configuration. |
| 4 | +This guide covers the patterns for passing and accessing environment variables. |
| 5 | + |
| 6 | +## Accessing Environment Variables in Tools |
| 7 | + |
| 8 | +Use `os.environ` or `os.getenv()` to read environment variables in your tool functions: |
| 9 | + |
| 10 | +```python title="server.py" |
| 11 | +import os |
| 12 | + |
| 13 | +from mcp.server import MCPServer |
| 14 | + |
| 15 | +mcp = MCPServer("my-server") |
| 16 | + |
| 17 | + |
| 18 | +@mcp.tool() |
| 19 | +def search(query: str) -> str: |
| 20 | + """Search using an external API.""" |
| 21 | + api_key = os.environ["SEARCH_API_KEY"] # (1)! |
| 22 | + # use api_key to call your service... |
| 23 | + return f"Results for: {query}" |
| 24 | + |
| 25 | + |
| 26 | +@mcp.tool() |
| 27 | +def summarize(text: str) -> str: |
| 28 | + """Summarize text using the configured model.""" |
| 29 | + model = os.getenv("MODEL_NAME", "gpt-4o") # (2)! |
| 30 | + return f"Summary (via {model}): {text[:100]}..." |
| 31 | +``` |
| 32 | + |
| 33 | +1. Raises `KeyError` if the variable is not set. Use this for required configuration. |
| 34 | +2. Returns a default value if the variable is not set. Use this for optional configuration. |
| 35 | + |
| 36 | +## How Environment Variables Reach Your Server |
| 37 | + |
| 38 | +### Claude Desktop |
| 39 | + |
| 40 | +When configuring a server in Claude Desktop's `claude_desktop_config.json`, |
| 41 | +environment variables are specified in the `env` field: |
| 42 | + |
| 43 | +```json |
| 44 | +{ |
| 45 | + "mcpServers": { |
| 46 | + "my-server": { |
| 47 | + "command": "uv", |
| 48 | + "args": ["run", "server.py"], |
| 49 | + "env": { |
| 50 | + "SEARCH_API_KEY": "sk-...", |
| 51 | + "MODEL_NAME": "gpt-4o" |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +The `mcp install` command can set these for you: |
| 59 | + |
| 60 | +```bash |
| 61 | +# Set individual variables |
| 62 | +mcp install server.py -v SEARCH_API_KEY=sk-... -v MODEL_NAME=gpt-4o |
| 63 | + |
| 64 | +# Or load from a .env file |
| 65 | +mcp install server.py -f .env |
| 66 | +``` |
| 67 | + |
| 68 | +### Running Directly |
| 69 | + |
| 70 | +When running your server directly, pass environment variables using standard shell mechanisms: |
| 71 | + |
| 72 | +```bash |
| 73 | +# Inline |
| 74 | +SEARCH_API_KEY=sk-... uv run server.py |
| 75 | + |
| 76 | +# Or export first |
| 77 | +export SEARCH_API_KEY=sk-... |
| 78 | +uv run server.py |
| 79 | +``` |
| 80 | + |
| 81 | +### Programmatic Clients |
| 82 | + |
| 83 | +When connecting to a stdio server programmatically, pass environment variables |
| 84 | +through `StdioServerParameters`: |
| 85 | + |
| 86 | +```python |
| 87 | +from mcp import ClientSession |
| 88 | +from mcp.client.stdio import StdioServerParameters, stdio_client |
| 89 | + |
| 90 | +params = StdioServerParameters( |
| 91 | + command="uv", |
| 92 | + args=["run", "server.py"], |
| 93 | + env={ |
| 94 | + "SEARCH_API_KEY": "sk-...", |
| 95 | + "MODEL_NAME": "gpt-4o", |
| 96 | + }, |
| 97 | +) |
| 98 | + |
| 99 | +async with stdio_client(params) as (read, write): |
| 100 | + async with ClientSession(read, write) as session: |
| 101 | + await session.initialize() |
| 102 | + # session is ready to use |
| 103 | +``` |
| 104 | + |
| 105 | +!!! note |
| 106 | + The stdio transport inherits a filtered set of environment variables from the parent |
| 107 | + process for security. Variables passed via the `env` parameter are merged on top of |
| 108 | + these defaults. |
| 109 | + |
| 110 | +## MCPServer Settings |
| 111 | + |
| 112 | +`MCPServer` uses [Pydantic Settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) |
| 113 | +and recognizes the following `MCP_`-prefixed environment variables: |
| 114 | + |
| 115 | +| Variable | Default | Description | |
| 116 | +|----------|---------|-------------| |
| 117 | +| `MCP_DEBUG` | `false` | Enable debug logging | |
| 118 | +| `MCP_LOG_LEVEL` | `INFO` | Set the log level | |
| 119 | +| `MCP_WARN_ON_DUPLICATE_TOOLS` | `true` | Warn when registering duplicate tool names | |
| 120 | +| `MCP_WARN_ON_DUPLICATE_RESOURCES` | `true` | Warn when registering duplicate resources | |
| 121 | +| `MCP_WARN_ON_DUPLICATE_PROMPTS` | `true` | Warn when registering duplicate prompts | |
| 122 | + |
| 123 | +These can also be set in a `.env` file, which `MCPServer` loads automatically. |
0 commit comments