π The fast, Pythonic way to build MCP servers and clients.
Disambiguate colliding parameter flags in generate-cli (#6311)
Mohit Sharma4cc16efa0a13
diff --git a/fastmcp_slim/fastmcp/cli/generate.py b/fastmcp_slim/fastmcp/cli/generate.pyindex 05360ad12..ab827a6c8 100644--- a/fastmcp_slim/fastmcp/cli/generate.py+++ b/fastmcp_slim/fastmcp/cli/generate.py@@ -4,6 +4,7 @@ import keywordimport reimport sysimport textwrap+from collections import defaultdictfrom pathlib import Pathfrom typing import Annotated, Anyfrom urllib.parse import urlparse@@ -207,11 +208,83 @@ def _to_python_identifier(name: str) -> str:return safe+def _resolve_tool_param_flags(+ properties: dict[str, Any],+) -> dict[str, tuple[str, str | None]]:+ """Resolve CLI flags for tool parameters, disambiguating colliding names.++ Returns a mapping of ``prop_name -> (cli_flag, explicit_name)`` where:+ - ``cli_flag`` is the flag string for documentation / invocation (e.g. ``--user-id`` or ``--userId``).+ - ``explicit_name`` is the explicit flag to pass to ``cyclopts.Parameter(name=...)``,+ or ``None`` if the parameter can rely on cyclopts' default name transform.+ """+ items: list[tuple[str, str, str, str]] = []+ for prop_name in properties:+ safe_name = _to_python_identifier(prop_name)+ if safe_name in {"_call_tool", "isinstance", "json", "str"}:+ safe_name = f"{safe_name}_"+ default_flag = _param_to_cli_flag(prop_name)+ norm_key = default_flag.replace("_", "-")+ items.append((prop_name, safe_name, default_flag, norm_key))++ groups: dict[str, list[tuple[str, str, str]]] = defaultdict(list)+ for prop_name, safe_name, default_flag, norm_key in items:+ groups[norm_key].append((prop_name, safe_name, default_flag))++ # Fast path: no collisions anywhere in the tool+ if all(len(group) == 1 for group in groups.values()):+ return {+ prop_name: (default_flag, None) for prop_name, _, default_flag, _ in items+ }++ result: dict[str, tuple[str, str | None]] = {}+ assigned_norms: set[str] = set()++ # Pass 1: non-colliding flags claim their default+ for norm_key, group_items in groups.items():+ if len(group_items) == 1:+ prop_name, _safe_name, default_flag = group_items[0]+ result[prop_name] = (default_flag, None)+ assigned_norms.add(norm_key)++ # Pass 2: resolve colliding flags+ for norm_key, group_items in groups.items():+ if len(group_items) <= 1:+ continue++ # If exactly one matches the default flag in lowercase snake_case, let it keep the default+ exact_default = [+ (p, s, d)+ for p, s, d in group_items+ if f"--{p.replace('_', '-')}".lower() == d and p.islower()+ ]+ default_prop = exact_default[0][0] if len(exact_default) == 1 else None++ for prop_name, safe_name, default_flag in group_items:+ if prop_name == default_prop and norm_key not in assigned_norms:+ result[prop_name] = (default_flag, None)+ assigned_norms.add(norm_key)+ else:+ candidate = f"--{safe_name.rstrip('_')}"+ norm = candidate.replace("_", "-")+ if norm in assigned_norms:+ suffix = 2+ while f"{norm}-{suffix}" in assigned_norms:+ suffix += 1+ candidate = f"{candidate}-{suffix}"+ norm = candidate.replace("_", "-")+ assigned_norms.add(norm)+ result[prop_name] = (candidate, candidate)++ return result++def _tool_function_source(tool: mcp_types.Tool) -> str:"""Generate the source for a single ``@call_tool_app.command`` function."""schema = tool.input_schemaproperties: dict[str, Any] = schema.get("properties", {})required = set(schema.get("required", []))+ param_flags = _resolve_tool_param_flags(properties)# Build parameter lines and track which need JSON parsingparam_lines: list[str] = []@@ -248,11 +321,12 @@ def _tool_function_source(tool: mcp_types.Tool) -> str:help_text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n"))+ _, explicit_name = param_flags[prop_name]+ flag_arg = f'name="{explicit_name}", ' if explicit_name else ""+# Build parameter annotationif is_required:- annotation = (- f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]'- )+ annotation = f'Annotated[{py_type}, cyclopts.Parameter({flag_arg}help="{help_escaped}")]'param_lines.append(f" {safe_name}: {annotation},")else:default = prop_schema.get("default")@@ -260,15 +334,15 @@ def _tool_function_source(tool: mcp_types.Tool) -> str:# For complex types with defaults, serialize to JSON stringif needs_json:default_str = pydantic_core.to_json(default, fallback=str).decode()- annotation = f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]'+ annotation = f'Annotated[{py_type}, cyclopts.Parameter({flag_arg}help="{help_escaped}")]'param_lines.append(f" {safe_name}: {annotation} = {default_str!r},")else:- annotation = f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]'+ annotation = f'Annotated[{py_type}, cyclopts.Parameter({flag_arg}help="{help_escaped}")]'param_lines.append(f" {safe_name}: {annotation} = {default!r},")else:- annotation = f'Annotated[{py_type} | None, cyclopts.Parameter(help="{help_escaped}")]'+ annotation = f'Annotated[{py_type} | None, cyclopts.Parameter({flag_arg}help="{help_escaped}")]'param_lines.append(f" {safe_name}: {annotation} = None,")call_args.append(f"{prop_name!r}: {safe_name}")@@ -613,11 +687,12 @@ def _tool_skill_section(tool: mcp_types.Tool, cli_filename: str) -> str:schema = tool.input_schemaproperties: dict[str, Any] = schema.get("properties", {})required = set(schema.get("required", []))+ param_flags = _resolve_tool_param_flags(properties)# Build example invocation flagsflag_parts_list: list[str] = []for p, p_schema in properties.items():- flag = _param_to_cli_flag(p)+ flag = param_flags[p][0]schema_type = p_schema.get("type")is_bool = schema_type == "boolean" or (isinstance(schema_type, list) and "boolean" in schema_type@@ -634,7 +709,7 @@ def _tool_skill_section(tool: mcp_types.Tool, cli_filename: str) -> str:# Build parameter table rowsrows: list[str] = []for prop_name, prop_schema in properties.items():- flag = f"`{_param_to_cli_flag(prop_name)}`"+ flag = f"`{param_flags[prop_name][0]}`"type_label = _schema_type_label(prop_schema).replace("|", "\\|")is_required = "yes" if prop_name in required else "no"description = prop_schema.get("description", "")diff --git a/tests/cli/test_generate_cli.py b/tests/cli/test_generate_cli.pyindex 33326aff4..f31e15164 100644--- a/tests/cli/test_generate_cli.py+++ b/tests/cli/test_generate_cli.py@@ -15,6 +15,7 @@ from fastmcp.cli.client import Clientfrom fastmcp.cli.generate import (_derive_server_name,_param_to_cli_flag,+ _resolve_tool_param_flags,_schema_to_python_type,_schema_type_label,_to_python_identifier,@@ -974,3 +975,104 @@ class TestGenerateSkillContent:content = generate_skill_content("My Weather API", "cli.py", [])assert "# My Weather API CLI" in contentassert 'name: "my-weather-api-cli"' in content+++# ---------------------------------------------------------------------------+# _resolve_tool_param_flags & Flag Collisions (Issue #6294)+# ---------------------------------------------------------------------------+++class TestResolveToolParamFlags:+ def test_no_collisions(self):+ flags = _resolve_tool_param_flags({"city": {}, "max_days": {}})+ assert flags == {+ "city": ("--city", None),+ "max_days": ("--max-days", None),+ }++ def test_snake_and_camel_collision(self):+ flags = _resolve_tool_param_flags({"user_id": {}, "userId": {}})+ assert flags["user_id"] == ("--user-id", None)+ assert flags["userId"] == ("--userId", "--userId")++ def test_order_independence(self):+ flags = _resolve_tool_param_flags({"userId": {}, "user_id": {}})+ assert flags["user_id"] == ("--user-id", None)+ assert flags["userId"] == ("--userId", "--userId")++ def test_multiple_collisions(self):+ flags = _resolve_tool_param_flags({"user_id": {}, "userId": {}, "UserId": {}})+ assert flags["user_id"] == ("--user-id", None)+ assert flags["userId"] == ("--userId", "--userId")+ assert flags["UserId"] == ("--UserId", "--UserId")++ def test_case_collision(self):+ flags = _resolve_tool_param_flags({"id": {}, "Id": {}})+ assert flags["id"] == ("--id", None)+ assert flags["Id"] == ("--Id", "--Id")++ def test_colliding_params_emit_explicit_flag_and_execute(self):+ tool = mcp_types.Tool(+ name="lookup",+ input_schema={+ "properties": {+ "user_id": {"type": "string"},+ "userId": {"type": "string"},+ },+ "required": ["user_id", "userId"],+ },+ )+ source = _tool_function_source(tool)+ assert 'user_id: Annotated[str, cyclopts.Parameter(help="")]' in source+ assert (+ 'userId: Annotated[str, cyclopts.Parameter(name="--userId", help="")]'+ in source+ )+ compile(source, "<test>", "exec")++ # End-to-end execution with generate_cli_script and Cyclopts+ script = generate_cli_script(+ server_name="users",+ server_spec="server.py",+ transport_code='"http://localhost"',+ extra_imports=set(),+ tools=[tool],+ )+ compile(script, "<generated>", "exec")++ namespace: dict[str, Any] = {}+ exec(script, namespace)+ call_tool_app = namespace["call_tool_app"]++ called = []++ async def mock_call_tool(name, args):+ called.append((name, args))++ namespace["_call_tool"] = mock_call_tool++ call_tool_app(+ ["lookup", "--user-id", "val1", "--userId", "val2"],+ result_action="return_value",+ )+ assert called == [("lookup", {"user_id": "val1", "userId": "val2"})]++ def test_colliding_flags_in_skill_generation(self):+ tools = [+ mcp_types.Tool(+ name="lookup",+ input_schema={+ "type": "object",+ "properties": {+ "user_id": {"type": "string"},+ "userId": {"type": "string"},+ },+ "required": ["user_id", "userId"],+ },+ )+ ]+ content = generate_skill_content("users", "cli.py", tools)+ assert "--user-id <value>" in content+ assert "--userId <value>" in content+ assert "| `--user-id` |" in content+ assert "| `--userId` |" in content