π The fast, Pythonic way to build MCP servers and clients.
Remove run_with_uv() and inline UV logic in cli.py (#1770)
Jeremiah Lowin54b7a3b79fed
diff --git a/src/fastmcp/cli/cli.py b/src/fastmcp/cli/cli.pyindex 7fdfebf56..32edb362c 100644--- a/src/fastmcp/cli/cli.py+++ b/src/fastmcp/cli/cli.py@@ -465,39 +465,53 @@ async def run(needs_uv = config.environment.build_command(test_cmd) != test_cmd and not skip_envif needs_uv:- # Use uv run subprocess - always use run_with_uv which handles output correctly+ # Build the inner fastmcp command+ inner_cmd = ["fastmcp", "run", server_spec]++ # Add transport options to the inner command+ if final_transport:+ inner_cmd.extend(["--transport", final_transport])+ # Only add HTTP-specific options for non-stdio transports+ if final_transport != "stdio":+ if final_host:+ inner_cmd.extend(["--host", final_host])+ if final_port:+ inner_cmd.extend(["--port", str(final_port)])+ if final_path:+ inner_cmd.extend(["--path", final_path])+ if final_log_level:+ inner_cmd.extend(["--log-level", final_log_level])+ if no_banner:+ inner_cmd.append("--no-banner")+ # Add skip-env flag to prevent infinite recursion+ inner_cmd.append("--skip-env")++ # Add server args if any+ if final_server_args:+ inner_cmd.append("--")+ inner_cmd.extend(final_server_args)++ # Build the full uv command using the config's environment+ cmd = config.environment.build_command(inner_cmd)++ # Set marker to prevent infinite loops when subprocess calls FastMCP again+ env = os.environ | {"FASTMCP_UV_SPAWNED": "1"}++ # Run the command+ logger.debug(f"Running command: {' '.join(cmd)}")try:- run_module.run_with_uv(- server_spec=server_spec,- python_version=config.environment.python,- with_packages=config.environment.dependencies,- with_requirements=(- Path(config.environment.requirements)- if config.environment.requirements- else None- ),- project=(- Path(config.environment.project)- if config.environment.project- else None- ),- transport=final_transport,- host=final_host,- port=final_port,- path=final_path,- log_level=final_log_level,- show_banner=not no_banner,- editable=config.environment.editable,- )- except Exception as e:+ process = subprocess.run(cmd, check=True, env=env)+ sys.exit(process.returncode)+ except subprocess.CalledProcessError as e:logger.error(f"Failed to run: {e}",extra={"server_spec": server_spec,"error": str(e),+ "returncode": e.returncode,},)- sys.exit(1)+ sys.exit(e.returncode)else:# Use direct import for backwards compatibilitytry:@@ -643,6 +657,7 @@ async def inspect("fastmcp","inspect",server_spec,+ "--skip-env", # Prevent infinite recursion]# Add format and output flags if specifieddiff --git a/src/fastmcp/cli/run.py b/src/fastmcp/cli/run.pyindex 2cbfb4ab1..f2712ca1c 100644--- a/src/fastmcp/cli/run.py+++ b/src/fastmcp/cli/run.py@@ -1,9 +1,7 @@"""FastMCP run command implementation with enhanced type hints."""import json-import osimport re-import subprocessimport sysfrom pathlib import Pathfrom typing import Any, Literal@@ -15,7 +13,6 @@ from fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.mcp_server_config import (MCPServerConfig,)-from fastmcp.utilities.mcp_server_config.v1.environments.uv import UVEnvironmentfrom fastmcp.utilities.mcp_server_config.v1.sources.filesystem import FileSystemSourcelogger = get_logger("cli.run")@@ -31,86 +28,6 @@ def is_url(path: str) -> bool:return bool(url_pattern.match(path))-def run_with_uv(- server_spec: str,- python_version: str | None = None,- with_packages: list[str] | None = None,- with_requirements: Path | None = None,- project: Path | None = None,- transport: TransportType | None = None,- host: str | None = None,- port: int | None = None,- path: str | None = None,- log_level: LogLevelType | None = None,- show_banner: bool = True,- editable: str | list[str] | None = None,-) -> None:- """Run a MCP server using uv run subprocess.-- This function is called when we need to set up a Python environment with specific- dependencies before running the server. The config parsing and merging should already- be done by the caller.-- Args:- server_spec: Python file, object specification (file:obj), config file, or URL- python_version: Python version to use (e.g. "3.10")- with_packages: Additional packages to install- with_requirements: Requirements file to use- project: Run the command within the given project directory- transport: Transport protocol to use- host: Host to bind to when using http transport- port: Port to bind to when using http transport- path: Path to bind to when using http transport- log_level: Log level- show_banner: Whether to show the server banner- editable: Editable package paths- """-- env_config = UVEnvironment(- python=python_version,- dependencies=with_packages if with_packages else None,- requirements=str(with_requirements.resolve()) if with_requirements else None,- project=str(project.resolve()) if project else None,- editable=editable- if isinstance(editable, list)- else ([editable] if editable else None),- )-- # Build the inner fastmcp command (environment variable prevents infinite recursion)- inner_cmd = ["fastmcp", "run", server_spec]-- # Add transport options to the inner command- if transport:- inner_cmd.extend(["--transport", transport])- # Only add HTTP-specific options for non-stdio transports- if transport != "stdio":- if host:- inner_cmd.extend(["--host", host])- if port:- inner_cmd.extend(["--port", str(port)])- if path:- inner_cmd.extend(["--path", path])- if log_level:- inner_cmd.extend(["--log-level", log_level])- if not show_banner:- inner_cmd.append("--no-banner")-- # Build the full uv command- cmd = env_config.build_command(inner_cmd)-- # Set marker to prevent infinite loops when subprocess calls FastMCP again- env = os.environ | {"FASTMCP_UV_SPAWNED": "1"}-- # Run the command- logger.debug(f"Running command: {' '.join(cmd)}")- try:- process = subprocess.run(cmd, check=True, env=env)- sys.exit(process.returncode)- except subprocess.CalledProcessError as e:- logger.error(f"Failed to run server: {e}")- sys.exit(e.returncode)--def create_client_server(url: str) -> Any:"""Create a FastMCP server from a client URL.diff --git a/tests/cli/test_run_with_uv.py b/tests/cli/test_run_with_uv.pydeleted file mode 100644index 0cf6aedda..000000000--- a/tests/cli/test_run_with_uv.py+++ /dev/null@@ -1,257 +0,0 @@-"""Tests for the run_with_uv function and related functionality."""--import subprocess-from pathlib import Path-from unittest.mock import Mock, patch--import pytest--from fastmcp.cli.run import run_with_uv---class TestRunWithUv:- """Test the run_with_uv function."""-- @patch("subprocess.run")- def test_run_with_uv_basic(self, mock_run):- """Test basic run_with_uv execution."""- mock_run.return_value = Mock(returncode=0)-- with pytest.raises(SystemExit) as exc_info:- run_with_uv("server.py")-- assert isinstance(exc_info.value, SystemExit)- assert exc_info.value.code == 0-- # Check the command that was called- mock_run.assert_called_once()- cmd = mock_run.call_args[0][0]- env = mock_run.call_args.kwargs.get("env", {})-- # With no environment config, the command should be returned unchanged- expected = [- "fastmcp",- "run",- "server.py",- ]- assert cmd == expected- # Check that the environment marker is set- assert env.get("FASTMCP_UV_SPAWNED") == "1"-- @patch("subprocess.run")- def test_run_with_uv_python_version(self, mock_run):- """Test run_with_uv with Python version."""- mock_run.return_value = Mock(returncode=0)-- with pytest.raises(SystemExit) as exc_info:- run_with_uv("server.py", python_version="3.11")-- assert isinstance(exc_info.value, SystemExit)- assert exc_info.value.code == 0-- cmd = mock_run.call_args[0][0]- expected = [- "uv",- "run",- "--python",- "3.11",- "fastmcp",- "run",- "server.py",- ]- assert cmd == expected-- @patch("subprocess.run")- def test_run_with_uv_project(self, mock_run):- """Test run_with_uv with project directory."""- mock_run.return_value = Mock(returncode=0)- # Use an absolute path that works on all platforms- project_path = Path.cwd() / "my" / "project"-- with pytest.raises(SystemExit) as exc_info:- run_with_uv("server.py", project=project_path)-- assert isinstance(exc_info.value, SystemExit)- assert exc_info.value.code == 0-- cmd = mock_run.call_args[0][0]- # Check the basic structure- assert cmd[:3] == ["uv", "run", "--project"]- # Check that the project path is absolute- assert Path(cmd[3]).is_absolute()- # Check the rest of the command- assert cmd[4:] == [- "fastmcp",- "run",- "server.py",- ]-- @patch("subprocess.run")- def test_run_with_uv_with_packages(self, mock_run):- """Test run_with_uv with additional packages."""- mock_run.return_value = Mock(returncode=0)-- with pytest.raises(SystemExit) as exc_info:- run_with_uv("server.py", with_packages=["pandas", "numpy"])-- assert isinstance(exc_info.value, SystemExit)- assert exc_info.value.code == 0-- cmd = mock_run.call_args[0][0]- expected = [- "uv",- "run",- "--with",- "numpy",- "--with",- "pandas",- "fastmcp",- "run",- "server.py",- ]- assert cmd == expected-- @patch("subprocess.run")- def test_run_with_uv_with_requirements(self, mock_run):- """Test run_with_uv with requirements file."""- mock_run.return_value = Mock(returncode=0)- req_path = Path("requirements.txt")-- with pytest.raises(SystemExit) as exc_info:- run_with_uv("server.py", with_requirements=req_path)-- assert isinstance(exc_info.value, SystemExit)- assert exc_info.value.code == 0-- cmd = mock_run.call_args[0][0]- expected = [- "uv",- "run",- "--with-requirements",- str(req_path.resolve()), # auto-resolved to absolute path- "fastmcp",- "run",- "server.py",- ]- assert cmd == expected-- @patch("subprocess.run")- def test_run_with_uv_transport_options(self, mock_run):- """Test run_with_uv with transport-related options."""- mock_run.return_value = Mock(returncode=0)-- with pytest.raises(SystemExit) as exc_info:- run_with_uv(- "server.py",- transport="http",- host="localhost",- port=8080,- path="/api",- log_level="DEBUG",- show_banner=False,- )-- assert isinstance(exc_info.value, SystemExit)- assert exc_info.value.code == 0-- cmd = mock_run.call_args[0][0]- # With no environment config, no uv run prefix- expected = [- "fastmcp",- "run",- "server.py",- "--transport",- "http",- "--host",- "localhost",- "--port",- "8080",- "--path",- "/api",- "--log-level",- "DEBUG",- "--no-banner",- ]- assert cmd == expected-- @patch("subprocess.run")- def test_run_with_uv_all_options(self, mock_run):- """Test run_with_uv with all options combined."""- mock_run.return_value = Mock(returncode=0)-- # Use an absolute path that works on all platforms- project_path = Path.cwd() / "workspace"-- with pytest.raises(SystemExit) as exc_info:- run_with_uv(- "server.py",- python_version="3.10",- project=project_path,- with_packages=["pandas"],- with_requirements=Path("reqs.txt"),- transport="http",- port=9000,- show_banner=False,- )-- assert isinstance(exc_info.value, SystemExit)- assert exc_info.value.code == 0-- cmd = mock_run.call_args[0][0]-- # When project is specified, Python version is not included- # Build expected command step by step- expected_start = ["uv", "run", "--project"]-- # Check start and that project path is absolute- assert cmd[:3] == expected_start- assert Path(cmd[3]).is_absolute()-- # Find the index where packages and requirements start- next_idx = 4- assert cmd[next_idx : next_idx + 2] == ["--with", "pandas"]- next_idx += 2- assert cmd[next_idx : next_idx + 1] == ["--with-requirements"]- next_idx += 1- # Check requirements path is absolute- assert Path(cmd[next_idx]).is_absolute()- assert Path(cmd[next_idx]).name == "reqs.txt"- next_idx += 1-- # Rest should be the fastmcp command with options- assert cmd[next_idx:] == [- "fastmcp",- "run",- "server.py",- "--transport",- "http",- "--port",- "9000",- "--no-banner",- ]-- @patch("subprocess.run")- def test_run_with_uv_error_handling(self, mock_run):- """Test run_with_uv error handling."""- mock_run.side_effect = subprocess.CalledProcessError(1, ["uv", "run"])-- with pytest.raises(SystemExit) as exc_info:- run_with_uv("server.py")-- assert isinstance(exc_info.value, SystemExit)- assert exc_info.value.code == 1-- @patch("fastmcp.cli.run.logger")- @patch("subprocess.run")- def test_run_with_uv_logging(self, mock_run, mock_logger):- """Test that run_with_uv logs the command."""- mock_run.return_value = Mock(returncode=0)-- with pytest.raises(SystemExit):- run_with_uv("server.py", python_version="3.11")-- # Check that debug logging was called with the command- mock_logger.debug.assert_called()- call_args = mock_logger.debug.call_args[0][0]- assert "Running command:" in call_args- assert "uv run --python 3.11" in call_args