π The fast, Pythonic way to build MCP servers and clients.
Preserve empty arrays in generated commands (#5961)
Dali6f2200baf705
diff --git a/fastmcp_slim/fastmcp/cli/generate.py b/fastmcp_slim/fastmcp/cli/generate.pyindex b8bf35f95..a61925ec9 100644--- a/fastmcp_slim/fastmcp/cli/generate.py+++ b/fastmcp_slim/fastmcp/cli/generate.py@@ -264,13 +264,8 @@ def _tool_function_source(tool: mcp_types.Tool) -> str:annotation = f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]'param_lines.append(f" {safe_name}: {annotation} = {default!r},")else:- # For list types, default to empty list; others default to None- if py_type.startswith("list["):- annotation = f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]'- param_lines.append(f" {safe_name}: {annotation} = [],")- else:- annotation = f'Annotated[{py_type} | None, cyclopts.Parameter(help="{help_escaped}")]'- param_lines.append(f" {safe_name}: {annotation} = None,")+ annotation = f'Annotated[{py_type} | None, cyclopts.Parameter(help="{help_escaped}")]'+ param_lines.append(f" {safe_name}: {annotation} = None,")call_args.append(f"{prop_name!r}: {safe_name}")@@ -417,12 +412,8 @@ def generate_cli_script(async def _call_tool(tool_name: str, arguments: dict) -> None:- # Filter out None values and empty lists (defaults for optional array params)- filtered = {- k: v- for k, v in arguments.items()- if v is not None and (not isinstance(v, list) or len(v) > 0)- }+ # None represents an omitted optional argument; empty arrays are values.+ filtered = {k: v for k, v in arguments.items() if v is not None}async with Client(CLIENT_SPEC) as client:result = await client.call_tool(tool_name, filtered, raise_on_error=False)_print_tool_result(result)diff --git a/tests/cli/test_generate_cli.py b/tests/cli/test_generate_cli.pyindex 0836c18f5..400b2b251 100644--- a/tests/cli/test_generate_cli.py+++ b/tests/cli/test_generate_cli.py@@ -279,8 +279,8 @@ class TestToolFunctionSource:)source = _tool_function_source(tool)# Should use list[str] type with help metadata- assert "tags: Annotated[list[str]" in source- assert "= []" in source+ assert "tags: Annotated[list[str] | None" in source+ assert "= None" in source# Should not have JSON parsing for simple arraysassert "json.loads" not in sourcecompile(source, "<test>", "exec")diff --git a/tests/cli/test_generate_cli_empty_arrays.py b/tests/cli/test_generate_cli_empty_arrays.pynew file mode 100644index 000000000..fec39ea02--- /dev/null+++ b/tests/cli/test_generate_cli_empty_arrays.py@@ -0,0 +1,85 @@+"""Generated commands must distinguish empty arrays from omitted arguments."""++from typing import Any++import pytest+from pydantic import Field++from fastmcp import Client, FastMCP+from fastmcp.cli.generate import generate_cli_script+++async def generated_app(server: FastMCP) -> Any:+ async with Client(server) as client:+ tools = await client.list_tools()+ source = generate_cli_script(+ "arrays", "arrays", repr("http://unused/mcp"), set(), tools+ )+ namespace: dict[str, Any] = {"__name__": "generated_cli"}+ exec(compile(source, "<generated>", "exec"), namespace)+ namespace["CLIENT_SPEC"] = server+ return namespace["app"]+++async def test_required_json_array_preserves_empty_value() -> None:+ server = FastMCP("Arrays")+ received: list[list[dict[str, int]]] = []++ @server.tool+ def count_items(items: list[dict[str, int]]) -> int:+ received.append(items)+ return len(items)++ app = await generated_app(server)+ await app.run_async(+ ["call-tool", "count_items", "--items", "[]"], result_action="return_value"+ )++ assert received == [[]]++[email protected]("value", ["[]", '[{"id":2}]'])+async def test_optional_json_array_preserves_explicit_override(value: str) -> None:+ server = FastMCP("Arrays")+ received: list[list[dict[str, int]]] = []++ @server.tool+ def count_items(items: list[dict[str, int]] = [{"id": 1}]) -> int:+ received.append(items)+ return len(items)++ app = await generated_app(server)+ await app.run_async(+ ["call-tool", "count_items", "--items", value], result_action="return_value"+ )++ assert received == ([[]] if value == "[]" else [[{"id": 2}]])+++ ("arguments", "expected"),+ [+ ([], ["server-default"]),+ (["--empty-tags"], []),+ (["--tags", "one", "--tags", "two"], ["one", "two"]),+ ],+)+async def test_simple_array_preserves_omission_and_explicit_values(+ arguments: list[str], expected: list[str]+) -> None:+ server = FastMCP("Arrays")+ received: list[list[str]] = []++ @server.tool+ def tag_items(+ tags: list[str] = Field(default_factory=lambda: ["server-default"]),+ ) -> int:+ received.append(tags)+ return len(tags)++ app = await generated_app(server)+ await app.run_async(+ ["call-tool", "tag_items", *arguments], result_action="return_value"+ )++ assert received == [expected]