openai/codex · error

Environment variable {env_var} for MCP server '{server_name}

Error message

Environment variable {env_var} for MCP server '{server_name}' contains invalid Unicode

What it means

std::env::var reports VarError::NotUnicode when the variable's raw OS bytes are not valid UTF-8, and resolve_bearer_token requires a UTF-8 string. The variable exists and is non-empty, but its contents are byte sequences a Rust String cannot hold, so the MCP server fails to start.

Source

Thrown at codex-rs/codex-mcp/src/rmcp_client.rs:852

) -> Result<Option<String>> {
    let Some(env_var) = bearer_token_env_var else {
        return Ok(None);
    };

    match env::var(env_var) {
        Ok(value) => {
            if value.is_empty() {
                Err(anyhow!(
                    "Environment variable {env_var} for MCP server '{server_name}' is empty"
                ))
            } else {
                Ok(Some(value))
            }
        }
        Err(env::VarError::NotPresent) => Err(anyhow!(
            "Environment variable {env_var} for MCP server '{server_name}' is not set"
        )),
        Err(env::VarError::NotUnicode(_)) => Err(anyhow!(
            "Environment variable {env_var} for MCP server '{server_name}' contains invalid Unicode"
        )),
    }
}

fn validate_mcp_server_name(server_name: &str) -> Result<()> {
    let re = regex_lite::Regex::new(r"^[a-zA-Z0-9_-]+$")?;
    if !re.is_match(server_name) {
        return Err(anyhow!(
            "Invalid MCP server name '{server_name}': must match pattern {pattern}",
            pattern = re.as_str()
        ));
    }
    Ok(())
}

#[instrument(level = "trace", skip_all, fields(server_name = %server_name))]
async fn start_server_task(

View on GitHub (pinned to 339751715c)

Solutions

  1. Re-export the variable with clean UTF-8: encode binary keys as hex/base64 if the server accepts them, e.g. export FOO_TOKEN=$(head -c 32 /dev/urandom | base64)
  2. Confirm the corruption: printenv FOO_TOKEN | xxd | head and look for invalid sequences (lone continuation bytes, stray 0x80-0xBF)
  3. Regenerate the token from the provider as an ASCII/UTF-8 string if it was mangled in transit
  4. Fix the provisioning script that sets the variable so it never writes undecoded binary

Example fix

# before: raw binary bytes land in the env var
export FOO_TOKEN="$(head -c 32 /dev/urandom)"

# after: ASCII-safe encoding
export FOO_TOKEN="$(head -c 32 /dev/urandom | base64)"
Defensive patterns

Strategy: validation

Validate before calling

# Reject non-UTF-8 values before launch
python3 - <<'EOF'
import os
v = os.environb.get(b"FOO_TOKEN")
if v is not None:
    try:
        v.decode("utf-8")
    except UnicodeDecodeError:
        raise SystemExit("FOO_TOKEN is not valid UTF-8")
EOF

Prevention

When it happens

Trigger: bearer_token_env_var points at a variable written as raw bytes: export FOO=$(head -c16 /dev/urandom), export FOO=$(cat token.bin) reading a binary keyfile, a value saved in a legacy non-UTF-8 codepage, or env mangled by a provisioning script.

Common situations: Binary API keys used verbatim instead of hex/base64; Windows codepage-1252 tokens copied into WSL; provisioning scripts piping keyfiles directly into env vars.

Related errors


AI-assisted analysis of openai/codex@339751715c (2026-08-25). Data as JSON: /api/errors/8ae2140b6db0364f. Report an issue: GitHub.