π The fast, Pythonic way to build MCP servers and clients.
Reject empty env var keys (#4410)
fengguodong0d8844d5a7c7
diff --git a/fastmcp_slim/fastmcp/cli/cli.py b/fastmcp_slim/fastmcp/cli/cli.pyindex c78e024af..6c85c8093 100644--- a/fastmcp_slim/fastmcp/cli/cli.py+++ b/fastmcp_slim/fastmcp/cli/cli.py@@ -66,6 +66,9 @@ def _parse_env_var(env_var: str) -> tuple[str, str]:logger.error("Invalid environment variable format. Must be KEY=VALUE")sys.exit(1)key, value = env_var.split("=", 1)+ if not key.strip():+ logger.error("Invalid environment variable format. KEY cannot be empty")+ sys.exit(1)return key.strip(), value.strip()diff --git a/fastmcp_slim/fastmcp/cli/install/shared.py b/fastmcp_slim/fastmcp/cli/install/shared.pyindex df22f5bbf..84026ed69 100644--- a/fastmcp_slim/fastmcp/cli/install/shared.py+++ b/fastmcp_slim/fastmcp/cli/install/shared.py@@ -47,6 +47,11 @@ def parse_env_var(env_var: str) -> tuple[str, str]:)sys.exit(1)key, value = env_var.split("=", 1)+ if not key.strip():+ print(+ f"[red]Invalid environment variable format: '[bold]{env_var}[/bold]'. KEY cannot be empty[/red]"+ )+ sys.exit(1)return key.strip(), value.strip()diff --git a/tests/cli/test_shared.py b/tests/cli/test_shared.pyindex b01ad2cfd..17ab19c7f 100644--- a/tests/cli/test_shared.py+++ b/tests/cli/test_shared.py@@ -1,4 +1,7 @@+import pytest+from fastmcp.cli.cli import _parse_env_var+from fastmcp.cli.install.shared import parse_env_varclass TestEnvVarParsing:@@ -27,3 +30,10 @@ class TestEnvVarParsing:key, value = _parse_env_var("EMPTY_VAR=")assert key == "EMPTY_VAR"assert value == ""++ @pytest.mark.parametrize("parser", [_parse_env_var, parse_env_var])+ def test_parse_env_var_empty_key_exits(self, parser):+ """Environment variable names cannot be empty."""+ with pytest.raises(SystemExit) as exc_info:+ parser(" =value")+ assert exc_info.value.code == 1