Skip to content
AgenticAIWiki
  1. Learn
  2. Part 7
  3. 36. Configuring MCP
  4. 36.2

Lesson 36.2 · 2 of 5 · 4 min read · Reviewed 24 Nov 2026

Environment variable expansion and secrets

By the end, you can

  • Keep secrets out of MCP config with environment variables.
  • Expand variables with defaults.

.mcp.json is shared, so it must work for everyone without containing anyone’s secrets.

Expansion

Claude CodeClaude Code: Anthropic’s agentic coding tool that works in your terminal, IDE and CI, reading and editing code and running commands. expands environment variables in command, args, env, url and headers:

"env": {
  "TRACKER_TOKEN": "${TRACKER_TOKEN}",
  "TRACKER_URL": "${TRACKER_URL:-https://tracker.example.com}"
}
  • ${VAR} uses the value from the person’s environment.
  • ${VAR:-default} falls back to a default if it’s not set. Use defaults only for non-secret values.

If a required variable isn’t set, the server fails to start, which is better than starting with the wrong credentials.

Where the values live

In each person’s shell profile, a local .env that git ignores, or a secrets manager. In CIContinuous integration (CI): Automatically building and testing code on every change, usually in a hosted pipeline., use the platform’s secret store.

If a secret leaks

Rotate it at once. Removing it from the latest commit isn’t enough, because it stays in git history.

Key points

  • Reference secrets as ${VAR} in .mcp.json; each person sets the value in their own environment.
  • ${VAR:-default} gives a fallback for non-secret values like URLs.
  • Never commit tokens; rotate any that leak.
Hands-on labRuns in the Playground

Expand variables in an MCP config

Implement ${VAR} and ${VAR:-default} expansion for an .mcp.json, fail clearly on missing secrets, and flag literal secrets.

You will have: An expand() function and a config checker that print the expanded config and any problems found.

Steps

  1. Read the sample config and the simulated environment dictionary.
  2. Write expand(text, env) with a regular expression for ${NAME} and ${NAME:-default}.
  3. Raise an error naming the variable when a ${NAME} has no value and no default.
  4. Write check_config() to flag any env value that is a literal (no ${...}) whose key looks secret: TOKEN, KEY or SECRET.
  5. Also flag a secret-looking key that uses a :- default.
  6. Run it against the good config and the risky config.

Done when

  • The good config expands TRACKER_URL to its default and TRACKER_TOKEN from the environment.
  • Removing TRACKER_TOKEN from the environment gives a clear missing-variable error.
  • The risky config prints two problems: one literal secret and one secret with a default.

Open in the Playground No API key needed.

Starter code (Python)
import json, re

env = {"TRACKER_TOKEN": "sim-token-from-my-shell"}   # pretend this is your shell environment

good = {"tracker": {"command": "npx", "args": ["-y", "@example/tracker-mcp"],
        "env": {"TRACKER_TOKEN": "${TRACKER_TOKEN}", "TRACKER_URL": "${TRACKER_URL:-https://tracker.example.com}"}}}
risky = {"tracker": {"command": "npx", "args": ["-y", "@example/tracker-mcp"],
         "env": {"TRACKER_TOKEN": "trk-pasted-by-mistake", "DOCS_API_KEY": "${DOCS_API_KEY:-shared-team-value}"}}}

PATTERN = re.compile(r"\$\{([A-Z0-9_]+)(?::-([^}]*))?\}")

def expand(text, env):
    # TODO: replace each ${NAME} or ${NAME:-default}; raise KeyError(NAME) if neither a value nor a default exists
    return text

def check_config(servers):
    problems = []
    # TODO: for each env entry whose key contains TOKEN, KEY or SECRET:
    #   - a value with no ${...} is a literal secret
    #   - a value with ":-" gives a secret a committed default
    return problems

print(json.dumps({k: expand(v, env) for k, v in good["tracker"]["env"].items()}, indent=1))
print("risky problems:", check_config(risky))
Show a solution
import json, re

env = {"TRACKER_TOKEN": "sim-token-from-my-shell"}   # pretend this is your shell environment

good = {"tracker": {"command": "npx", "args": ["-y", "@example/tracker-mcp"],
        "env": {"TRACKER_TOKEN": "${TRACKER_TOKEN}", "TRACKER_URL": "${TRACKER_URL:-https://tracker.example.com}"}}}
risky = {"tracker": {"command": "npx", "args": ["-y", "@example/tracker-mcp"],
         "env": {"TRACKER_TOKEN": "trk-pasted-by-mistake", "DOCS_API_KEY": "${DOCS_API_KEY:-shared-team-value}"}}}

PATTERN = re.compile(r"\$\{([A-Z0-9_]+)(?::-([^}]*))?\}")

def expand(text, env):
    def sub(m):
        name, default = m.group(1), m.group(2)
        if name in env:
            return env[name]
        if default is not None:
            return default
        raise KeyError(name)
    return PATTERN.sub(sub, text)

def check_config(servers):
    problems = []
    for server, cfg in servers.items():
        for key, value in cfg.get("env", {}).items():
            if not any(w in key for w in ("TOKEN", "KEY", "SECRET")):
                continue
            if not PATTERN.search(value):
                problems.append(f"{server}.{key}: literal secret in config")
            elif ":-" in value:
                problems.append(f"{server}.{key}: secret has a committed default")
    return problems

print(json.dumps({k: expand(v, env) for k, v in good["tracker"]["env"].items()}, indent=1))
try:
    expand("${TRACKER_TOKEN}", {})
except KeyError as e:
    print("missing variable:", e.args[0], "(server would fail to start)")
print("good problems:", check_config(good))
for p in check_config(risky):
    print("risky:", p)
Quick checkWhich .mcp.json line is safe to commit?
How sure are you?
Pick an answer and how sure you are