🚀 The fast, Pythonic way to build MCP servers and clients.
cli: read MCP and fastmcp.json config files as utf-8 (#5345)
nate nowack0e4c8aa3a283
diff --git a/fastmcp_slim/fastmcp/cli/cli.py b/fastmcp_slim/fastmcp/cli/cli.pyindex 22c0c4596..fbc155927 100644--- a/fastmcp_slim/fastmcp/cli/cli.py+++ b/fastmcp_slim/fastmcp/cli/cli.py@@ -881,7 +881,7 @@ async def inspect(if server_spec.endswith(".json") and config is None:# This might be an MCPConfig, check the filetry:- with open(Path(server_spec)) as f:+ with open(Path(server_spec), encoding="utf-8") as f:data = json.load(f)if "mcpServers" in data:logger.error("MCPConfig files are not supported by inspect command")diff --git a/fastmcp_slim/fastmcp/cli/client.py b/fastmcp_slim/fastmcp/cli/client.pyindex 73fe46815..cf9946de7 100644--- a/fastmcp_slim/fastmcp/cli/client.py+++ b/fastmcp_slim/fastmcp/cli/client.py@@ -137,7 +137,7 @@ def _resolve_json_spec(path: Path) -> str | dict[str, Any]:sys.exit(1)try:- data = json.loads(path.read_text())+ data = json.loads(path.read_text(encoding="utf-8"))except json.JSONDecodeError as exc:console.print(f"[bold red]Error:[/bold red] Invalid JSON in {path}: {exc}")sys.exit(1)diff --git a/fastmcp_slim/fastmcp/cli/install/claude_desktop.py b/fastmcp_slim/fastmcp/cli/install/claude_desktop.pyindex 780b97c36..ef68ddf34 100644--- a/fastmcp_slim/fastmcp/cli/install/claude_desktop.py+++ b/fastmcp_slim/fastmcp/cli/install/claude_desktop.py@@ -115,7 +115,7 @@ def install_claude_desktop(if config_file.exists():import json- content = config_file.read_text().strip()+ content = config_file.read_text(encoding="utf-8").strip()if content:config = json.loads(content)if "mcpServers" in config and name in config["mcpServers"]:diff --git a/fastmcp_slim/fastmcp/cli/install/shared.py b/fastmcp_slim/fastmcp/cli/install/shared.pyindex 84026ed69..79b8d3263 100644--- a/fastmcp_slim/fastmcp/cli/install/shared.py+++ b/fastmcp_slim/fastmcp/cli/install/shared.py@@ -79,7 +79,7 @@ async def process_common_args(sys.exit(1)try:- with open(config_path) as f:+ with open(config_path, encoding="utf-8") as f:data = json.load(f)# Check if it's an MCPConfig (has mcpServers key)diff --git a/fastmcp_slim/fastmcp/cli/run.py b/fastmcp_slim/fastmcp/cli/run.pyindex 0d12f14c2..ef8f09f29 100644--- a/fastmcp_slim/fastmcp/cli/run.py+++ b/fastmcp_slim/fastmcp/cli/run.py@@ -114,7 +114,7 @@ def create_client_server(url: str) -> Any:def create_mcp_config_server(mcp_config_path: Path) -> FastMCP[None]:"""Create a FastMCP server from a MCPConfig."""- with mcp_config_path.open() as src:+ with mcp_config_path.open(encoding="utf-8") as src:mcp_config = json.load(src)server = create_proxy(mcp_config)@@ -175,7 +175,7 @@ async def run_command(elif server_spec.endswith(".json"):# Load JSON and check which type of config it isconfig_path = Path(server_spec)- with open(config_path) as f:+ with open(config_path, encoding="utf-8") as f:data = json.load(f)# Check if it's an MCPConfig first (has canonical mcpServers key)diff --git a/fastmcp_slim/fastmcp/utilities/cli.py b/fastmcp_slim/fastmcp/utilities/cli.pyindex ad03691c5..3e24cc14c 100644--- a/fastmcp_slim/fastmcp/utilities/cli.py+++ b/fastmcp_slim/fastmcp/utilities/cli.py@@ -73,7 +73,7 @@ def load_and_merge_config(config_path = Path(resolved_spec)if config_path.exists():try:- with open(config_path) as f:+ with open(config_path, encoding="utf-8") as f:data = json.load(f)# Check if it's an MCPConfig first (has canonical mcpServers key)diff --git a/tests/cli/test_config_encoding.py b/tests/cli/test_config_encoding.pynew file mode 100644index 000000000..f3855e029--- /dev/null+++ b/tests/cli/test_config_encoding.py@@ -0,0 +1,102 @@+"""Regression tests for GH-5317: CLI config files are UTF-8 regardless of locale."""++import builtins+import io+import json+from pathlib import Path+from typing import Any++import pytest++from fastmcp.cli.client import _resolve_json_spec+from fastmcp.cli.install.claude_desktop import install_claude_desktop+from fastmcp.cli.install.shared import process_common_args+from fastmcp.cli.run import create_mcp_config_server+from fastmcp.utilities.cli import load_and_merge_config++ARABIC_PATH = "C:\\Users\\فاطمة\\notes.js"+GREETING = "Olá José"+++def cp1252_locale(monkeypatch: pytest.MonkeyPatch) -> None:+ """Make text reads without an explicit encoding decode as cp1252, as they+ do on Windows with a non-UTF-8 system code page."""+ real_open = builtins.open++ def locale_open(+ file: Any,+ mode: str = "r",+ buffering: int = -1,+ encoding: str | None = None,+ *args: Any,+ **kwargs: Any,+ ) -> Any:+ if "b" not in mode and encoding in (None, "locale"):+ encoding = "cp1252"+ return real_open(file, mode, buffering, encoding, *args, **kwargs)++ def text_encoding(encoding: str | None, stacklevel: int = 2) -> str:+ return encoding or "cp1252"++ monkeypatch.setattr(builtins, "open", locale_open)+ monkeypatch.setattr(io, "text_encoding", text_encoding)+++def _write_utf8_json(path: Path, data: dict[str, Any]) -> None:+ path.write_bytes(json.dumps(data, ensure_ascii=False).encode("utf-8"))+++def _mcp_config() -> dict[str, Any]:+ return {+ "mcpServers": {+ "demo": {+ "command": "node",+ "args": [ARABIC_PATH],+ "env": {"GREETING": GREETING},+ }+ }+ }++[email protected]("cp1252_locale")+class TestConfigFilesReadAsUtf8:+ def test_client_resolves_mcp_config(self, tmp_path: Path):+ path = tmp_path / "mcp.json"+ _write_utf8_json(path, _mcp_config())++ assert _resolve_json_spec(path) == _mcp_config()++ def test_run_creates_mcp_config_server(self, tmp_path: Path):+ path = tmp_path / "mcp.json"+ _write_utf8_json(path, _mcp_config())++ create_mcp_config_server(path)++ def test_load_and_merge_fastmcp_json(self, tmp_path: Path):+ path = tmp_path / "fastmcp.json"+ _write_utf8_json(path, {"source": {"path": ARABIC_PATH}})++ config, _ = load_and_merge_config(str(path))++ assert config.source.path == ARABIC_PATH++ async def test_install_reads_fastmcp_json(self, tmp_path: Path):+ path = tmp_path / "fastmcp.json"+ (tmp_path / "فاطمة.py").write_text("", encoding="utf-8")+ _write_utf8_json(path, {"source": {"path": "فاطمة.py"}})++ file, *_ = await process_common_args(str(path), None, None, None, None)++ assert file == tmp_path / "فاطمة.py"++ def test_install_claude_desktop_merges_existing_config(self, tmp_path: Path):+ config_file = tmp_path / "claude_desktop_config.json"+ _write_utf8_json(config_file, _mcp_config())++ assert install_claude_desktop(+ tmp_path / "server.py", None, "demo", config_path=tmp_path+ )++ config = json.loads(config_file.read_bytes().decode("utf-8"))+ assert config["mcpServers"]["demo"]["env"] == {"GREETING": GREETING}