Skip to content

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

fix: preserve CRLF descriptions in generated CLI parameter help (#6075)

Daehyun Cho(Chris)e8f81f03e50e
diff --git a/fastmcp_slim/fastmcp/cli/generate.py b/fastmcp_slim/fastmcp/cli/generate.py
index ab827a6c8..623b187e4 100644
--- a/fastmcp_slim/fastmcp/cli/generate.py
+++ b/fastmcp_slim/fastmcp/cli/generate.py
@@ -316,17 +316,12 @@ def _tool_function_source(tool: mcp_types.Tool) -> str:
help_text = f"{help_text}\\n{schema_help}" if help_text else schema_help
json_params.append((prop_name, safe_name))
- # Escape special characters in help text
- help_escaped = (
- 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 annotation
if is_required:
- annotation = f'Annotated[{py_type}, cyclopts.Parameter({flag_arg}help="{help_escaped}")]'
+ annotation = f"Annotated[{py_type}, cyclopts.Parameter({flag_arg}help={help_text!r})]"
param_lines.append(f" {safe_name}: {annotation},")
else:
default = prop_schema.get("default")
@@ -334,15 +329,15 @@ def _tool_function_source(tool: mcp_types.Tool) -> str:
# For complex types with defaults, serialize to JSON string
if needs_json:
default_str = pydantic_core.to_json(default, fallback=str).decode()
- annotation = f'Annotated[{py_type}, cyclopts.Parameter({flag_arg}help="{help_escaped}")]'
+ annotation = f"Annotated[{py_type}, cyclopts.Parameter({flag_arg}help={help_text!r})]"
param_lines.append(
f" {safe_name}: {annotation} = {default_str!r},"
)
else:
- annotation = f'Annotated[{py_type}, cyclopts.Parameter({flag_arg}help="{help_escaped}")]'
+ annotation = f"Annotated[{py_type}, cyclopts.Parameter({flag_arg}help={help_text!r})]"
param_lines.append(f" {safe_name}: {annotation} = {default!r},")
else:
- annotation = f'Annotated[{py_type} | None, cyclopts.Parameter({flag_arg}help="{help_escaped}")]'
+ annotation = f"Annotated[{py_type} | None, cyclopts.Parameter({flag_arg}help={help_text!r})]"
param_lines.append(f" {safe_name}: {annotation} = None,")
call_args.append(f"{prop_name!r}: {safe_name}")
diff --git a/tests/cli/test_generate_cli.py b/tests/cli/test_generate_cli.py
index f31e15164..45d9492e2 100644
--- a/tests/cli/test_generate_cli.py
+++ b/tests/cli/test_generate_cli.py
@@ -308,9 +308,9 @@ class TestToolFunctionSource:
source = _tool_function_source(tool)
# Should use str type for complex object
assert "metadata: Annotated[str | None" in source
- # Should include JSON schema in help (with escaped quotes)
+ # Should include JSON schema in help
assert "JSON Schema:" in source
- assert '\\"type\\": \\"object\\"' in source
+ assert '"type": "object"' in source
# 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
@@ -1023,9 +1023,9 @@ class TestResolveToolParamFlags:
},
)
source = _tool_function_source(tool)
- assert 'user_id: Annotated[str, cyclopts.Parameter(help="")]' in source
+ assert "user_id: Annotated[str, cyclopts.Parameter(help='')]" in source
assert (
- 'userId: Annotated[str, cyclopts.Parameter(name="--userId", help="")]'
+ "userId: Annotated[str, cyclopts.Parameter(name=\"--userId\", help='')]"
in source
)
compile(source, "<test>", "exec")
diff --git a/tests/cli/test_generate_cli_help.py b/tests/cli/test_generate_cli_help.py
new file mode 100644
index 000000000..13abb2b7c
--- /dev/null
+++ b/tests/cli/test_generate_cli_help.py
@@ -0,0 +1,140 @@
+"""Generated parameter help must preserve descriptions as Python string literals."""
+
+from inspect import get_annotations
+from typing import Annotated, Any
+
+import pytest
+from pydantic import Field
+
+from fastmcp import Client, FastMCP
+from fastmcp.cli.generate import generate_cli_script
+
+
[email protected]("newline", ["\r\n", "\r", "\n"])
+async def test_parameter_help_preserves_line_endings(newline: str) -> None:
+ description = f"First \"line\"{newline}Second 'line' at C:\\tools β€” μ„€λͺ…"
+ server = FastMCP("Descriptions")
+ received: list[tuple[str, dict[str, str], str, dict[str, str] | None]] = []
+
+ @server.tool
+ def record(
+ message: Annotated[str, Field(description=description)],
+ options: Annotated[dict[str, str], Field(description=description)] = {"x": "y"},
+ label: Annotated[str, Field(description=description)] = "default",
+ optional: Annotated[
+ dict[str, str] | None, Field(description=description)
+ ] = None,
+ ) -> None:
+ received.append((message, options, label, optional))
+
+ async with Client(server) as client:
+ tools = await client.list_tools()
+ script = generate_cli_script(
+ server_name="descriptions",
+ server_spec="descriptions",
+ 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
+ app = namespace["app"]
+ # Python 3.10's get_type_hints adds Optional around parameters defaulted to None.
+ annotations = get_annotations(app["call-tool"]["record"].default_command)
+ for name in ("message", "label"):
+ assert annotations[name].__metadata__[0].help == description
+ for name in ("options", "optional"):
+ assert annotations[name].__metadata__[0].help.startswith(description)
+
+ await app.run_async(
+ ["call-tool", "record", "--message", "hello"], result_action="return_value"
+ )
+ await app.run_async(
+ [
+ "call-tool",
+ "record",
+ "--message",
+ "hi",
+ "--options",
+ '{"a": "b"}',
+ "--label",
+ "override",
+ "--optional",
+ '{"z": "q"}',
+ ],
+ result_action="return_value",
+ )
+ assert received == [
+ ("hello", {"x": "y"}, "default", None),
+ ("hi", {"a": "b"}, "override", {"z": "q"}),
+ ]
+
+
[email protected]("newline", ["\r\n", "\r", "\n"])
+async def test_parameter_help_preserves_explicit_flags(newline: str) -> None:
+ description = f"First \"line\"{newline}Second 'line' at C:\\tools β€” μ„€λͺ…"
+ server = FastMCP("Flag descriptions")
+ received: list[tuple[str, str, dict[str, str], str, dict[str, str] | None]] = []
+
+ @server.tool(name="app")
+ def record(
+ user_id: str,
+ userId: Annotated[str, Field(description=description)],
+ meta_data: dict[str, str] = {"x": "y"},
+ metaData: Annotated[dict[str, str], Field(description=description)] = {
+ "x": "y"
+ },
+ option_name: str = "default",
+ optionName: Annotated[str, Field(description=description)] = "default",
+ extra_data: dict[str, str] | None = None,
+ extraData: Annotated[
+ dict[str, str] | None, Field(description=description)
+ ] = None,
+ ) -> None:
+ received.append((user_id, userId, metaData, optionName, extraData))
+
+ async with Client(server) as client:
+ tools = await client.list_tools()
+ script = generate_cli_script(
+ server_name="Flag descriptions",
+ server_spec="descriptions",
+ 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
+ app = namespace["app"]
+ annotations = get_annotations(app["call-tool"]["app"].default_command)
+ for name in ("userId", "optionName"):
+ assert annotations[name].__metadata__[0].help == description
+ for name in ("metaData", "extraData"):
+ assert annotations[name].__metadata__[0].help.startswith(description)
+
+ await app.run_async(
+ ["call-tool", "app", "--user-id", "snake", "--userId", "camel"],
+ result_action="return_value",
+ )
+ await app.run_async(
+ [
+ "call-tool",
+ "app",
+ "--user-id",
+ "s",
+ "--userId",
+ "c",
+ "--metaData",
+ '{"a": "b"}',
+ "--optionName",
+ "override",
+ "--extraData",
+ '{"z": "q"}',
+ ],
+ result_action="return_value",
+ )
+ assert received == [
+ ("snake", "camel", {"x": "y"}, "default", None),
+ ("s", "c", {"a": "b"}, "override", {"z": "q"}),
+ ]