Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix(cli): preserve explicit null in generated tool commands (#6191)

Tianyuan Ding81bcbe00debf
diff --git a/docs/cli/generate-cli.mdx b/docs/cli/generate-cli.mdx
index 76bce4fdd..812e5b68d 100644
--- a/docs/cli/generate-cli.mdx
+++ b/docs/cli/generate-cli.mdx
@@ -83,6 +83,8 @@ python cli.py call-tool create_user \
--metadata '{"role": "admin", "dept": "engineering"}'
```
+For JSON-encoded parameters whose schema permits `null`, pass `--parameter null` to send an explicit null value. Omitting an optional flag remains distinct and allows its default to apply.
+
## Agent Skill
Alongside the CLI script, `generate-cli` writes a `SKILL.md` file β€” a [Claude Code agent skill](https://code.claude.com/docs/en/skills) that documents every tool's exact invocation syntax, parameter flags, types, and descriptions. An agent can pick up the CLI immediately without running `--help` or experimenting with flag names.
diff --git a/fastmcp_slim/fastmcp/cli/generate.py b/fastmcp_slim/fastmcp/cli/generate.py
index a359158a6..01d4f7ec6 100644
--- a/fastmcp_slim/fastmcp/cli/generate.py
+++ b/fastmcp_slim/fastmcp/cli/generate.py
@@ -293,17 +293,26 @@ def _tool_function_source(tool: mcp_types.Tool) -> str:
lines.append(") -> None:")
lines.append(f" '''{description}'''")
- # Add JSON parsing for complex parameters
- if json_params:
- lines.append(" # Parse JSON parameters")
- for _prop_name, safe_name in json_params:
+ dict_items = ", ".join(call_args)
+ if call_args:
+ arguments_name = "_arguments"
+ while arguments_name in seen_names:
+ arguments_name += "_"
+ lines.append(f" {arguments_name} = {{{dict_items}}}")
+ lines.append(" # Omit missing options before decoding explicit JSON null.")
+ lines.append(
+ f" {arguments_name} = {{k: v for k, v in {arguments_name}.items() "
+ f"if v is not None or k in {tuple(sorted(required))!r}}}"
+ )
+ for prop_name, _safe_name in json_params:
+ value = f"{arguments_name}[{prop_name!r}]"
lines.append(
- f" {safe_name} = json.loads({safe_name}) if isinstance({safe_name}, str) else {safe_name}"
+ f" if {prop_name!r} in {arguments_name} and isinstance({value}, str):"
)
- lines.append("")
-
- dict_items = ", ".join(call_args)
- lines.append(f" await _call_tool({tool.name!r}, {{{dict_items}}})")
+ lines.append(f" {value} = json.loads({value})")
+ lines.append(f" await _call_tool({tool.name!r}, {arguments_name})")
+ else:
+ lines.append(f" await _call_tool({tool.name!r}, {{}})")
lines.append("")
return "\n".join(lines)
@@ -407,10 +416,8 @@ def generate_cli_script(
async def _call_tool(tool_name: str, arguments: dict) -> None:
- # 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)
+ result = await client.call_tool(tool_name, arguments, raise_on_error=False)
_print_tool_result(result)
if result.is_error:
sys.exit(1)""")
diff --git a/tests/cli/test_generate_cli.py b/tests/cli/test_generate_cli.py
index eb4975efe..7751a0de9 100644
--- a/tests/cli/test_generate_cli.py
+++ b/tests/cli/test_generate_cli.py
@@ -160,7 +160,8 @@ class TestToolFunctionSource:
assert "async def greet(" in source
assert "name: Annotated[str" in source
assert "= None" not in source
- assert "_call_tool('greet', {'name': name})" in source
+ assert "_arguments = {'name': name}" in source
+ assert "_call_tool('greet', _arguments)" in source
def test_optional_param(self):
tool = mcp_types.Tool(
@@ -309,12 +310,9 @@ class TestToolFunctionSource:
# Should include JSON schema in help (with escaped quotes)
assert "JSON Schema:" in source
assert '\\"type\\": \\"object\\"' in source
- # Should have JSON parsing with isinstance check
- assert (
- "metadata = json.loads(metadata) if isinstance(metadata, str) else metadata"
- in source
- )
- # Should use the decoded value in the call
+ # Should decode retained JSON values without changing the raw parameter.
+ assert "isinstance(_arguments['metadata'], str)" in source
+ assert "_arguments['metadata'] = json.loads(_arguments['metadata'])" in source
assert "'metadata': metadata" in source
compile(source, "<test>", "exec")
@@ -339,10 +337,7 @@ class TestToolFunctionSource:
# Nested arrays need JSON parsing
assert "batches: Annotated[str" in source
assert "JSON Schema:" in source
- assert (
- "batches = json.loads(batches) if isinstance(batches, str) else batches"
- in source
- )
+ assert "_arguments['batches'] = json.loads(_arguments['batches'])" in source
compile(source, "<test>", "exec")
def test_complex_type_with_default(self):
@@ -363,7 +358,7 @@ class TestToolFunctionSource:
# pydantic_core.to_json produces compact JSON
assert '= \'{"timeout":30,"retry":true}\'' in source
# Should parse safely even with default
- assert "isinstance(options, str)" in source
+ assert "isinstance(_arguments['options'], str)" in source
compile(source, "<test>", "exec")
def test_name_collision_detection(self):
diff --git a/tests/cli/test_generate_cli_arguments.py b/tests/cli/test_generate_cli_arguments.py
index bc6a1b60e..ff08c6031 100644
--- a/tests/cli/test_generate_cli_arguments.py
+++ b/tests/cli/test_generate_cli_arguments.py
@@ -5,11 +5,96 @@ from unittest.mock import AsyncMock
import mcp_types
import pytest
+from pydantic import Field
from fastmcp import Client, FastMCP
from fastmcp.cli.generate import generate_cli_script
+async def generated_cli(server: FastMCP) -> dict[str, Any]:
+ async with Client(server) as client:
+ tools = await client.list_tools()
+ source = generate_cli_script(
+ "profiles", "profiles", 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
+
+
+ ("value", "expected"),
+ [("null", None), ("{}", {}), ('{"name":"Alice"}', {"name": "Alice"})],
+)
+async def test_required_json_parameter_preserves_null(
+ value: str, expected: dict[str, str] | None
+) -> None:
+ server = FastMCP("Profiles")
+ received: list[dict[str, str] | None] = []
+
+ @server.tool
+ def set_profile(profile: dict[str, str] | None) -> None:
+ received.append(profile)
+
+ namespace = await generated_cli(server)
+ await namespace["app"].run_async(
+ ["call-tool", "set_profile", "--profile", value],
+ result_action="return_value",
+ )
+
+ assert received == [expected]
+
+
[email protected]("use_default_factory", [False, True])
+ ("arguments", "expected"),
+ [
+ ([], {"name": "default"}),
+ (["--profile", "null"], None),
+ (["--profile", "{}"], {}),
+ (["--profile", '{"name":"Alice"}'], {"name": "Alice"}),
+ ],
+)
+async def test_optional_json_parameter_distinguishes_null_from_omission(
+ use_default_factory: bool,
+ arguments: list[str],
+ expected: dict[str, str] | None,
+) -> None:
+ server = FastMCP("Profiles")
+ received: list[dict[str, str] | None] = []
+ default = (
+ Field(default_factory=lambda: {"name": "default"})
+ if use_default_factory
+ else {"name": "default"}
+ )
+
+ @server.tool
+ def set_profile(profile: dict[str, str] | None = default) -> None:
+ received.append(profile)
+
+ namespace = await generated_cli(server)
+ await namespace["app"].run_async(
+ ["call-tool", "set_profile", *arguments], result_action="return_value"
+ )
+
+ assert received == [expected]
+
+
+async def test_json_parameters_do_not_collide_with_argument_dictionary() -> None:
+ server = FastMCP("Profiles")
+ received: list[tuple[dict[str, str] | None, str]] = []
+
+ @server.tool
+ def set_profile(_arguments: dict[str, str] | None, _arguments_: str) -> None:
+ received.append((_arguments, _arguments_))
+
+ namespace = await generated_cli(server)
+ await namespace["set_profile"](_arguments="null", _arguments_="keep")
+
+ assert received == [(None, "keep")]
+
+
@pytest.mark.parametrize("parsed_type", ["string", "object"])
@pytest.mark.parametrize("use_default", [False, True])
async def test_complex_parameter_preserves_parsed_suffix_parameter(