π The fast, Pythonic way to build MCP servers and clients.
Fix generate-cli commands for tools with a json parameter (#6032)
Andrei Vince2ae660a34114
diff --git a/fastmcp_slim/fastmcp/cli/generate.py b/fastmcp_slim/fastmcp/cli/generate.pyindex 1cf398666..a359158a6 100644--- a/fastmcp_slim/fastmcp/cli/generate.py+++ b/fastmcp_slim/fastmcp/cli/generate.py@@ -224,6 +224,10 @@ def _tool_function_source(tool: mcp_types.Tool) -> str:help_text = prop_schema.get("description", "")is_required = prop_name in requiredsafe_name = _to_python_identifier(prop_name)+ if safe_name in {"_call_tool", "isinstance", "json", "str"}:+ # The command body refers to these names, so a parameter must not+ # shadow them. Cyclopts drops the trailing underscore from the flag.+ safe_name = f"{safe_name}_"# Check for name collisions after sanitizationif safe_name in seen_names:diff --git a/tests/cli/test_generate_cli_arguments.py b/tests/cli/test_generate_cli_arguments.pyindex 0c835e2ac..bc6a1b60e 100644--- a/tests/cli/test_generate_cli_arguments.py+++ b/tests/cli/test_generate_cli_arguments.py@@ -6,6 +6,7 @@ from unittest.mock import AsyncMockimport mcp_typesimport pytest+from fastmcp import Client, FastMCPfrom fastmcp.cli.generate import generate_cli_script@@ -58,3 +59,32 @@ async def test_complex_parameter_preserves_parsed_suffix_parameter(),},)+++async def test_parameter_named_json_does_not_break_json_arguments() -> None:+ server = FastMCP("Requests")+ received: list[tuple[dict[str, int], dict[str, str]]] = []++ @server.tool+ def post(json: dict[str, int], headers: dict[str, str]) -> None:+ received.append((json, headers))++ async with Client(server) as client:+ tools = await client.list_tools()+ script = generate_cli_script(+ server_name="requests",+ server_spec="requests",+ 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", "post", "--json", '{"a": 1}', "--headers", '{"b": "2"}'],+ result_action="return_value",+ )++ assert received == [({"a": 1}, {"b": "2"})]