{"record":{"id":"8ae2140b6db0364f","repo":"openai/codex","slug":"environment-variable-env-var-for-mcp-server-se-8ae214","errorCode":null,"errorMessage":"Environment variable {env_var} for MCP server '{server_name}' contains invalid Unicode","messagePattern":"Environment variable (.+?) for MCP server '(.+?)' contains invalid Unicode","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"codex-rs/codex-mcp/src/rmcp_client.rs","lineNumber":852,"sourceCode":") -> Result<Option<String>> {\n    let Some(env_var) = bearer_token_env_var else {\n        return Ok(None);\n    };\n\n    match env::var(env_var) {\n        Ok(value) => {\n            if value.is_empty() {\n                Err(anyhow!(\n                    \"Environment variable {env_var} for MCP server '{server_name}' is empty\"\n                ))\n            } else {\n                Ok(Some(value))\n            }\n        }\n        Err(env::VarError::NotPresent) => Err(anyhow!(\n            \"Environment variable {env_var} for MCP server '{server_name}' is not set\"\n        )),\n        Err(env::VarError::NotUnicode(_)) => Err(anyhow!(\n            \"Environment variable {env_var} for MCP server '{server_name}' contains invalid Unicode\"\n        )),\n    }\n}\n\nfn validate_mcp_server_name(server_name: &str) -> Result<()> {\n    let re = regex_lite::Regex::new(r\"^[a-zA-Z0-9_-]+$\")?;\n    if !re.is_match(server_name) {\n        return Err(anyhow!(\n            \"Invalid MCP server name '{server_name}': must match pattern {pattern}\",\n            pattern = re.as_str()\n        ));\n    }\n    Ok(())\n}\n\n#[instrument(level = \"trace\", skip_all, fields(server_name = %server_name))]\nasync fn start_server_task(","sourceCodeStart":834,"sourceCodeEnd":870,"githubUrl":"https://github.com/openai/codex/blob/339751715c64496cb86246bfb3935f40e309dd3d/codex-rs/codex-mcp/src/rmcp_client.rs#L834-L870","documentation":"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.","triggerScenarios":"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.","commonSituations":"Binary API keys used verbatim instead of hex/base64; Windows codepage-1252 tokens copied into WSL; provisioning scripts piping keyfiles directly into env vars.","solutions":["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)","Confirm the corruption: printenv FOO_TOKEN | xxd | head and look for invalid sequences (lone continuation bytes, stray 0x80-0xBF)","Regenerate the token from the provider as an ASCII/UTF-8 string if it was mangled in transit","Fix the provisioning script that sets the variable so it never writes undecoded binary"],"exampleFix":"# before: raw binary bytes land in the env var\nexport FOO_TOKEN=\"$(head -c 32 /dev/urandom)\"\n\n# after: ASCII-safe encoding\nexport FOO_TOKEN=\"$(head -c 32 /dev/urandom | base64)\"","handlingStrategy":"validation","validationCode":"# Reject non-UTF-8 values before launch\npython3 - <<'EOF'\nimport os\nv = os.environb.get(b\"FOO_TOKEN\")\nif v is not None:\n    try:\n        v.decode(\"utf-8\")\n    except UnicodeDecodeError:\n        raise SystemExit(\"FOO_TOKEN is not valid UTF-8\")\nEOF","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Never put raw binary data in env vars; always hex or base64 encode","Encode keys at generation time, not at export time","Validate secrets decode as UTF-8 in provisioning scripts"],"tags":["mcp","codex","environment-variable","unicode","bearer-token","encoding"],"backgroundTag":"invalid-unicode-environment-variable","analyzedSha":"339751715c64496cb86246bfb3935f40e309dd3d","analyzedAt":"2026-08-25T05:35:09.876Z","schemaVersion":2},"datasetVersion":"2026-08-25T06:17:31.827Z"}