Spaces:
Running
Running
File size: 12,424 Bytes
8d034c6 80e65e7 6837525 b23a78c 8d034c6 b23a78c 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 6837525 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 8d034c6 ae4f592 80e65e7 ae4f592 80e65e7 b23a78c 80e65e7 b23a78c ad0696c 80e65e7 b23a78c 80e65e7 ae4f592 ad0696c b23a78c ae4f592 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | """Tests for the FastMCP CLI."""
import json
import sys
from pathlib import Path
from unittest.mock import call, patch
import pytest
from typer.testing import CliRunner
from fastmcp.cli.cli import _parse_env_var, _parse_file_path, app
@pytest.fixture
def mock_config(tmp_path):
"""Create a mock Claude config file."""
config = {"mcpServers": {}}
config_file = tmp_path / "claude_desktop_config.json"
config_file.write_text(json.dumps(config))
return config_file
@pytest.fixture
def server_file(tmp_path):
"""Create a server file."""
server_file = tmp_path / "server.py"
server_file.write_text(
"""from fastmcp import FastMCP
mcp = FastMCP("test")
"""
)
return server_file
@pytest.fixture
def mock_env_file(tmp_path):
"""Create a mock .env file."""
env_file = tmp_path / ".env"
env_file.write_text("FOO=bar\nBAZ=123")
return env_file
def test_parse_env_var():
"""Test parsing environment variables."""
assert _parse_env_var("FOO=bar") == ("FOO", "bar")
assert _parse_env_var("FOO=") == ("FOO", "")
assert _parse_env_var("FOO=bar baz") == ("FOO", "bar baz")
assert _parse_env_var("FOO = bar ") == ("FOO", "bar")
with pytest.raises(SystemExit):
_parse_env_var("invalid")
@pytest.mark.parametrize(
"args,expected_env",
[
# Basic env var
(
["--env-var", "FOO=bar"],
{"FOO": "bar"},
),
# Multiple env vars
(
["--env-var", "FOO=bar", "--env-var", "BAZ=123"],
{"FOO": "bar", "BAZ": "123"},
),
# Env var with spaces
(
["--env-var", "FOO=bar baz"],
{"FOO": "bar baz"},
),
],
)
def test_install_with_env_vars(mock_config, server_file, args, expected_env):
"""Test installing with environment variables."""
runner = CliRunner()
with patch("fastmcp.cli.claude.get_claude_config_path") as mock_config_path:
mock_config_path.return_value = mock_config.parent
result = runner.invoke(
app,
["install", str(server_file)] + args,
)
assert result.exit_code == 0
# Read the config file and check env vars
config = json.loads(mock_config.read_text())
assert "mcpServers" in config
assert len(config["mcpServers"]) == 1
server = next(iter(config["mcpServers"].values()))
assert server["env"] == expected_env
def test_parse_file_path_windows_drive():
"""Test parsing a Windows file path with a drive letter."""
file_spec = r"C:\path\to\file.txt"
with (
patch("pathlib.Path.exists", return_value=True),
patch("pathlib.Path.is_file", return_value=True),
):
file_path, server_object = _parse_file_path(file_spec)
assert file_path == Path(r"C:\path\to\file.txt").resolve()
assert server_object is None
def test_parse_file_path_with_object():
"""Test parsing a file path with an object specification."""
file_spec = "/path/to/file.txt:object"
with patch("sys.exit") as mock_exit:
_parse_file_path(file_spec)
# Check that sys.exit was called twice with code 1
assert mock_exit.call_count == 2
mock_exit.assert_has_calls([call(1), call(1)])
def test_parse_file_path_windows_with_object():
"""Test parsing a Windows file path with an object specification."""
file_spec = r"C:\path\to\file.txt:object"
with (
patch("pathlib.Path.exists", return_value=True),
patch("pathlib.Path.is_file", return_value=True),
):
file_path, server_object = _parse_file_path(file_spec)
assert file_path == Path(r"C:\path\to\file.txt").resolve()
assert server_object == "object"
def test_install_with_env_file(mock_config, server_file, mock_env_file):
"""Test installing with environment variables from a file."""
runner = CliRunner()
with patch("fastmcp.cli.claude.get_claude_config_path") as mock_config_path:
mock_config_path.return_value = mock_config.parent
result = runner.invoke(
app,
["install", str(server_file), "--env-file", str(mock_env_file)],
)
assert result.exit_code == 0
# Read the config file and check env vars
config = json.loads(mock_config.read_text())
assert "mcpServers" in config
assert len(config["mcpServers"]) == 1
server = next(iter(config["mcpServers"].values()))
assert server["env"] == {"FOO": "bar", "BAZ": "123"}
def test_install_preserves_existing_env_vars(mock_config, server_file):
"""Test that installing preserves existing environment variables."""
# Set up initial config with env vars
config = {
"mcpServers": {
"test": {
"command": "uv",
"args": [
"run",
"--with",
"fastmcp",
"fastmcp",
"run",
str(server_file),
],
"env": {"FOO": "bar", "BAZ": "123"},
}
}
}
mock_config.write_text(json.dumps(config))
runner = CliRunner()
with patch("fastmcp.cli.claude.get_claude_config_path") as mock_config_path:
mock_config_path.return_value = mock_config.parent
# Install with a new env var
result = runner.invoke(
app,
["install", str(server_file), "--env-var", "NEW=value"],
)
assert result.exit_code == 0
# Read the config file and check env vars are preserved
config = json.loads(mock_config.read_text())
server = next(iter(config["mcpServers"].values()))
assert server["env"] == {"FOO": "bar", "BAZ": "123", "NEW": "value"}
def test_install_updates_existing_env_vars(mock_config, server_file):
"""Test that installing updates existing environment variables."""
# Set up initial config with env vars
config = {
"mcpServers": {
"test": {
"command": "uv",
"args": [
"run",
"--with",
"fastmcp",
"fastmcp",
"run",
str(server_file),
],
"env": {"FOO": "bar", "BAZ": "123"},
}
}
}
mock_config.write_text(json.dumps(config))
runner = CliRunner()
with patch("fastmcp.cli.claude.get_claude_config_path") as mock_config_path:
mock_config_path.return_value = mock_config.parent
# Update an existing env var
result = runner.invoke(
app,
["install", str(server_file), "--env-var", "FOO=newvalue"],
)
assert result.exit_code == 0
# Read the config file and check env var was updated
config = json.loads(mock_config.read_text())
server = next(iter(config["mcpServers"].values()))
assert server["env"] == {"FOO": "newvalue", "BAZ": "123"}
def test_server_dependencies(mock_config, server_file):
"""Test that server dependencies are correctly handled."""
# Create a server file with dependencies
server_file = server_file.parent / "server_with_deps.py"
server_file.write_text(
"""from fastmcp import FastMCP
mcp = FastMCP("test", dependencies=["pandas", "numpy"])
"""
)
runner = CliRunner()
with patch("fastmcp.cli.claude.get_claude_config_path") as mock_config_path:
mock_config_path.return_value = mock_config.parent
result = runner.invoke(app, ["install", str(server_file)])
assert result.exit_code == 0
# Read the config file and check dependencies were added as --with args
config = json.loads(mock_config.read_text())
server = next(iter(config["mcpServers"].values()))
assert "--with" in server["args"]
assert "pandas" in server["args"]
assert "numpy" in server["args"]
def test_server_dependencies_empty(mock_config, server_file):
"""Test that server with no dependencies works correctly."""
runner = CliRunner()
with patch("fastmcp.cli.claude.get_claude_config_path") as mock_config_path:
mock_config_path.return_value = mock_config.parent
result = runner.invoke(app, ["install", str(server_file)])
assert result.exit_code == 0
# Read the config file and check only fastmcp is in --with args
config = json.loads(mock_config.read_text())
server = next(iter(config["mcpServers"].values()))
assert server["args"].count("--with") == 1
assert "fastmcp" in server["args"]
def test_dev_with_dependencies(mock_config, server_file):
"""Test that dev command handles dependencies correctly."""
server_file = server_file.parent / "server_with_deps.py"
server_file.write_text(
"""from fastmcp import FastMCP
mcp = FastMCP("test", dependencies=["pandas", "numpy"])
"""
)
runner = CliRunner()
with patch("subprocess.run") as mock_run:
mock_run.return_value.returncode = 0
result = runner.invoke(app, ["dev", str(server_file)])
assert result.exit_code == 0
if sys.platform == "win32":
# On Windows, expect two calls
assert mock_run.call_count == 2
assert mock_run.call_args_list[0] == call(
["npx.cmd", "--version"], check=True, capture_output=True, shell=True
)
# get the actual command and expected command without dependencies
actual_cmd = mock_run.call_args_list[1][0][0]
expected_start = [
"npx.cmd",
"@modelcontextprotocol/inspector",
"uv",
"run",
"--with",
"fastmcp",
]
expected_end = ["fastmcp", "run", str(server_file)]
# verify start and end of command
assert actual_cmd[: len(expected_start)] == expected_start
assert actual_cmd[-len(expected_end) :] == expected_end
# verify dependencies are present (order-independent)
deps_section = actual_cmd[len(expected_start) : -len(expected_end)]
assert all(
x in deps_section for x in ["--with", "numpy", "--with", "pandas"]
)
# Verify subprocess call kwargs, allowing for environment variables
call_kwargs = mock_run.call_args_list[1][1]
assert call_kwargs["check"] is True
assert call_kwargs["shell"] is True
assert isinstance(call_kwargs["env"], dict)
else:
# same verification for unix, just with different command prefix
actual_cmd = mock_run.call_args_list[0][0][0]
expected_start = [
"npx",
"@modelcontextprotocol/inspector",
"uv",
"run",
"--with",
"fastmcp",
]
expected_end = ["fastmcp", "run", str(server_file)]
assert actual_cmd[: len(expected_start)] == expected_start
assert actual_cmd[-len(expected_end) :] == expected_end
deps_section = actual_cmd[len(expected_start) : -len(expected_end)]
assert all(
x in deps_section for x in ["--with", "numpy", "--with", "pandas"]
)
# Verify subprocess call kwargs, allowing for environment variables
call_kwargs = mock_run.call_args_list[0][1]
assert call_kwargs["check"] is True
assert call_kwargs["shell"] is False
assert isinstance(call_kwargs["env"], dict)
def test_run_with_dependencies(mock_config, server_file):
"""Test that run command does not handle dependencies."""
# Create a server file with dependencies
server_file = server_file.parent / "server_with_deps.py"
server_file.write_text(
"""from fastmcp import FastMCP
mcp = FastMCP("test", dependencies=["pandas", "numpy"])
if __name__ == "__main__":
mcp.run()
"""
)
runner = CliRunner()
with patch("subprocess.run") as mock_run:
result = runner.invoke(app, ["run", str(server_file)])
assert result.exit_code == 0
# Run command should not call subprocess.run
mock_run.assert_not_called()
|