π The fast, Pythonic way to build MCP servers and clients.
Fix generated CLIs for tools named app, console or Client (#6056)
Andrei Vince2b71bdac5cc5
diff --git a/fastmcp_slim/fastmcp/cli/generate.py b/fastmcp_slim/fastmcp/cli/generate.pyindex 01d4f7ec6..05360ad12 100644--- a/fastmcp_slim/fastmcp/cli/generate.py+++ b/fastmcp_slim/fastmcp/cli/generate.py@@ -273,8 +273,10 @@ def _tool_function_source(tool: mcp_types.Tool) -> str:call_args.append(f"{prop_name!r}: {safe_name}")- # Function name: sanitize to valid Python identifier- fn_name = _to_python_identifier(tool.name)+ # Function name: prefixed so that no tool name can replace one of the+ # script's own globals or builtins (a tool named "app" would replace the+ # cyclopts app). The command name comes from name= below, not from this.+ fn_name = _to_python_identifier(f"tool_{tool.name}")# Docstring - use single-quoted docstrings to avoid triple-quote escaping issuesdescription = (tool.description or "").replace("\\", "\\\\").replace("'", "\\'")diff --git a/tests/cli/test_generate_cli.py b/tests/cli/test_generate_cli.pyindex 7751a0de9..33326aff4 100644--- a/tests/cli/test_generate_cli.py+++ b/tests/cli/test_generate_cli.py@@ -157,7 +157,7 @@ class TestToolFunctionSource:},)source = _tool_function_source(tool)- assert "async def greet(" in source+ assert "async def tool_greet(" in sourceassert "name: Annotated[str" in sourceassert "= None" not in sourceassert "_arguments = {'name': name}" in source@@ -204,7 +204,7 @@ class TestToolFunctionSource:input_schema={"properties": {}},)source = _tool_function_source(tool)- assert "async def ping(" in source+ assert "async def tool_ping(" in sourceassert "_call_tool('ping', {})" in sourcedef test_preserves_underscores(self):@@ -216,7 +216,7 @@ class TestToolFunctionSource:},)source = _tool_function_source(tool)- assert "async def get_forecast(" in source+ assert "async def tool_get_forecast(" in sourcedef test_sanitizes_tool_name(self):tool = mcp_types.Tool(@@ -224,7 +224,7 @@ class TestToolFunctionSource:input_schema={"properties": {}},)source = _tool_function_source(tool)- assert "async def my_tool_v2(" in source+ assert "async def tool_my_tool_v2(" in sourceassert "name='my.tool/v2'" in sourcedef test_sanitizes_param_name(self):@@ -448,8 +448,8 @@ class TestGenerateCliScript:extra_imports=set(),tools=self._make_tools(),)- assert "async def greet(" in script- assert "async def add_numbers(" in script+ assert "async def tool_greet(" in script+ assert "async def tool_add_numbers(" in scriptdef test_contains_generic_commands(self):script = generate_cli_script(@@ -621,8 +621,8 @@ class TestGenerateCliCommand:output = tmp_path / "cli.py"await generate_cli_command("test-server", str(output))content = output.read_text(encoding="utf-8")- assert "async def greet(" in content- assert "async def add(" in content+ assert "async def tool_greet(" in content+ assert "async def tool_add(" in content@pytest.mark.usefixtures("_patch_client")async def test_default_output_path(@@ -646,7 +646,7 @@ class TestGenerateCliCommand:await generate_cli_command("test-server", str(output), force=True)content = output.read_text(encoding="utf-8")assert content != "existing"- assert "async def greet(" in content+ assert "async def tool_greet(" in content@pytest.mark.skipif(sys.platform == "win32", reason="Unix executable bits N/A on Windows"diff --git a/tests/cli/test_generate_cli_arguments.py b/tests/cli/test_generate_cli_arguments.pyindex ff08c6031..f9045cc4e 100644--- a/tests/cli/test_generate_cli_arguments.py+++ b/tests/cli/test_generate_cli_arguments.py@@ -90,7 +90,7 @@ async def test_json_parameters_do_not_collide_with_argument_dictionary() -> Nonereceived.append((_arguments, _arguments_))namespace = await generated_cli(server)- await namespace["set_profile"](_arguments="null", _arguments_="keep")+ await namespace["tool_set_profile"](_arguments="null", _arguments_="keep")assert received == [(None, "keep")]@@ -133,7 +133,7 @@ async def test_complex_parameter_preserves_parsed_suffix_parameter(arguments = {"metadata_parsed": parsed_value}if not use_default:arguments["metadata"] = '{"role": "admin"}'- await namespace["create_user"](**arguments)+ await namespace["tool_create_user"](**arguments)call_tool.assert_awaited_once_with("create_user",diff --git a/tests/cli/test_generate_cli_tool_names.py b/tests/cli/test_generate_cli_tool_names.pynew file mode 100644index 000000000..c3ef82b94--- /dev/null+++ b/tests/cli/test_generate_cli_tool_names.py@@ -0,0 +1,38 @@+"""Generated commands must work whatever their tools are called."""++from typing import Any++import pytest++from fastmcp import Client, FastMCP+from fastmcp.cli.generate import generate_cli_script++[email protected]("name", ["app", "console", "Client"])+async def test_tool_named_like_a_script_global(name: str) -> None:+ server = FastMCP("Desktop")+ received: list[str] = []++ @server.tool(name=name)+ def record(text: str) -> str:+ received.append(text)+ return text++ async with Client(server) as client:+ tools = await client.list_tools()+ script = generate_cli_script(+ server_name="desktop",+ server_spec="desktop",+ transport_code=repr("http://unused/mcp"),+ extra_imports=set(),+ tools=tools,+ )+ namespace: dict[str, Any] = {"__name__": "generated_cli"}+ exec(compile(script, "<generated>", "exec"), namespace)+ namespace["CLIENT_SPEC"] = server++ await namespace["app"].run_async(+ ["call-tool", name, "--text", "hi"], result_action="return_value"+ )++ assert received == ["hi"]