Skip to content

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

Coerce optional parameters in fastmcp call by their non-null type (#5616)

Asem ahmed5789085df4d6
diff --git a/fastmcp_slim/fastmcp/cli/client.py b/fastmcp_slim/fastmcp/cli/client.py
index 33c1facb9..090b282ab 100644
--- a/fastmcp_slim/fastmcp/cli/client.py
+++ b/fastmcp_slim/fastmcp/cli/client.py
@@ -317,10 +317,27 @@ def _build_client(
# ---------------------------------------------------------------------------
+def _unwrap_nullable(schema: dict[str, Any]) -> dict[str, Any]:
+ """Reduce an optional schema (``X | None``) to the schema for ``X``."""
+
+ if "anyOf" in schema:
+ non_null = [s for s in schema["anyOf"] if s.get("type") != "null"]
+ if len(non_null) == 1:
+ return non_null[0]
+
+ schema_type = schema.get("type")
+ if isinstance(schema_type, list):
+ non_null_types = [t for t in schema_type if t != "null"]
+ if len(non_null_types) == 1:
+ return {**schema, "type": non_null_types[0]}
+
+ return schema
+
+
def coerce_value(raw: str, schema: dict[str, Any]) -> Any:
"""Coerce a string CLI value according to a JSON-Schema type hint."""
- schema_type = schema.get("type", "string")
+ schema_type = _unwrap_nullable(schema).get("type", "string")
if schema_type == "integer":
try:
diff --git a/tests/cli/test_client_commands.py b/tests/cli/test_client_commands.py
index 68672a8cc..5b04bb4d2 100644
--- a/tests/cli/test_client_commands.py
+++ b/tests/cli/test_client_commands.py
@@ -93,6 +93,38 @@ class TestCoerceValue:
def test_string_preserves_numeric_looking_values(self):
assert coerce_value("42", {"type": "string"}) == "42"
+ @pytest.mark.parametrize(
+ ("raw", "schema", "expected"),
+ [
+ ("[1, 2]", {"anyOf": [{"type": "array"}, {"type": "null"}]}, [1, 2]),
+ ('{"a": 1}', {"anyOf": [{"type": "null"}, {"type": "object"}]}, {"a": 1}),
+ ("42", {"anyOf": [{"type": "integer"}, {"type": "null"}]}, 42),
+ ("true", {"anyOf": [{"type": "boolean"}, {"type": "null"}]}, True),
+ ("[1, 2]", {"type": ["array", "null"]}, [1, 2]),
+ ("42", {"anyOf": [{"type": "string"}, {"type": "null"}]}, "42"),
+ ],
+ )
+ def test_optional_uses_non_null_type(self, raw, schema, expected):
+ """``X | None`` is coerced like ``X``."""
+ result = coerce_value(raw, schema)
+ assert result == expected
+ assert type(result) is type(expected)
+
+ def test_optional_invalid_value(self):
+ with pytest.raises(ValueError, match="Expected JSON array"):
+ coerce_value("not-json", {"anyOf": [{"type": "array"}, {"type": "null"}]})
+
+ @pytest.mark.parametrize(
+ "schema",
+ [
+ {"anyOf": [{"type": "integer"}, {"type": "string"}]},
+ {"anyOf": [{"type": "integer"}, {"type": "string"}, {"type": "null"}]},
+ {"type": ["integer", "string"]},
+ ],
+ )
+ def test_ambiguous_union_stays_string(self, schema):
+ assert coerce_value("42", schema) == "42"
+
# ---------------------------------------------------------------------------
# parse_tool_arguments
@@ -128,6 +160,22 @@ class TestParseToolArguments:
result = parse_tool_arguments(("query=a=b=c",), None, self.SCHEMA)
assert result == {"query": "a=b=c"}
+ def test_optional_array_parsed_as_json(self):
+ schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "tags": {
+ "anyOf": [
+ {"type": "array", "items": {"type": "string"}},
+ {"type": "null"},
+ ],
+ "default": None,
+ },
+ },
+ }
+ result = parse_tool_arguments(('tags=["a", "b"]',), None, schema)
+ assert result == {"tags": ["a", "b"]}
+
def test_invalid_arg_format_exits(self):
with pytest.raises(SystemExit):
parse_tool_arguments(("noequalssign",), None, self.SCHEMA)
@@ -591,6 +639,11 @@ def _build_test_server() -> FastMCP:
"""Add two numbers."""
return a + b
+ @server.tool
+ def total(values: list[int] | None = None) -> int:
+ """Sum an optional list of numbers."""
+ return sum(values or [])
+
@server.resource("test://greeting")
def greeting_resource() -> str:
"""A static greeting resource."""
@@ -667,6 +720,15 @@ class TestCallCommandCLI:
data = json.loads(captured.out)
assert data["is_error"] is False
+ @pytest.mark.usefixtures("_patch_client")
+ async def test_call_tool_optional_array(self, capsys: pytest.CaptureFixture[str]):
+ await call_command(
+ "fake://server", "total", "values=[1, 2, 3]", json_output=True
+ )
+ data = json.loads(capsys.readouterr().out)
+ assert data["is_error"] is False
+ assert data["structured_content"] == {"result": 6}
+
@pytest.mark.usefixtures("_patch_client")
async def test_call_tool_not_found(self):
with pytest.raises(SystemExit):