π The fast, Pythonic way to build MCP servers and clients.
fix(cli): parse JSON for non-string unions and accept null in call args (#6012)
Christian Sidak7257b660c8a5
diff --git a/fastmcp_slim/fastmcp/cli/client.py b/fastmcp_slim/fastmcp/cli/client.pyindex b0fabf898..5e6a190fb 100644--- a/fastmcp_slim/fastmcp/cli/client.py+++ b/fastmcp_slim/fastmcp/cli/client.py@@ -353,10 +353,72 @@ def _unwrap_nullable(schema: dict[str, Any]) -> dict[str, Any]:return schema+def _union_branches(schema: dict[str, Any]) -> list[dict[str, Any]] | None:+ """Return the ``anyOf``/``oneOf`` branches of a union schema, if any."""++ branches = schema.get("anyOf", schema.get("oneOf"))+ return branches if isinstance(branches, list) else None+++def _schema_allows_null(schema: dict[str, Any]) -> bool:+ """Return True if the schema permits a null/None value."""++ branches = _union_branches(schema)+ if branches is not None:+ return any(_schema_allows_null(s) for s in branches)++ schema_type = schema.get("type")+ if isinstance(schema_type, list):+ return "null" in schema_type+ return schema_type == "null"+++def _schema_may_be_string(schema: dict[str, Any]) -> bool:+ """Return True if a non-null value matching ``schema`` could be a string.++ Branches without a ``type`` (a ``$ref``, an enum, an unconstrained schema)+ are treated as possibly strings so the raw CLI input is preserved.+ """++ branches = _union_branches(schema)+ if branches is not None:+ return any(_schema_may_be_string(s) for s in branches)++ schema_type = schema.get("type")+ if schema_type is None:+ return True+ if isinstance(schema_type, list):+ return "string" in schema_type+ return schema_type == "string"++def coerce_value(raw: str, schema: dict[str, Any]) -> Any:"""Coerce a string CLI value according to a JSON-Schema type hint."""- schema_type = _unwrap_nullable(schema).get("type", "string")+ # ``null`` means None for nullable schemas, unless the value could also be+ # the literal string "null" (e.g. ``str | None``); use --input-json there.+ if (+ raw == "null"+ and _schema_allows_null(schema)+ and not _schema_may_be_string(schema)+ ):+ return None++ unwrapped = _unwrap_nullable(schema)++ # Unions with several non-null branches (``int | list[int]``, a+ # discriminated ``Cat | Dog``) have no top-level type. When no branch can+ # be a string, decode raw arrays and objects as JSON; anything else is+ # passed through for the server to validate.+ if _union_branches(unwrapped) is not None and "type" not in unwrapped:+ if not _schema_may_be_string(unwrapped) and raw[:1] in ("[", "{"):+ try:+ return json.loads(raw)+ except json.JSONDecodeError:+ pass+ return raw++ schema_type = unwrapped.get("type", "string")if schema_type == "integer":try:diff --git a/tests/cli/test_client_commands.py b/tests/cli/test_client_commands.pyindex 88ff48abe..23b2f3ed3 100644--- a/tests/cli/test_client_commands.py+++ b/tests/cli/test_client_commands.py@@ -3,13 +3,14 @@import jsonimport warningsfrom pathlib import Path-from typing import Any+from typing import Annotated, Any, Literalfrom unittest.mock import patchimport mcp_typesimport pytestfrom cryptography.fernet import Fernetfrom mcp.shared.auth import OAuthClientInformationFull, OAuthToken+from pydantic import BaseModel, Fieldfrom fastmcp import FastMCPfrom fastmcp.cli import client as client_module@@ -127,6 +128,99 @@ class TestCoerceValue:def test_ambiguous_union_stays_string(self, schema):assert coerce_value("42", schema) == "42"+ @pytest.mark.parametrize(+ ("raw", "schema", "expected"),+ [+ # null literal maps to None when schema allows null+ ("null", {"anyOf": [{"type": "integer"}, {"type": "null"}]}, None),+ ("null", {"anyOf": [{"type": "array"}, {"type": "null"}]}, None),+ ("null", {"type": ["integer", "null"]}, None),+ ("null", {"anyOf": [{"type": "null"}]}, None),+ ],+ )+ def test_null_literal_returns_none_when_nullable(self, raw, schema, expected):+ """``null`` maps to ``None`` when the schema allows it."""+ assert coerce_value(raw, schema) is None++ def test_null_literal_stays_string_when_not_nullable(self):+ """``null`` stays as a string when the schema does not allow null."""+ assert coerce_value("null", {"type": "string"}) == "null"++ @pytest.mark.parametrize(+ ("raw", "schema", "expected"),+ [+ # int | list[int]: JSON array is parsed, not passed as string+ ("[1, 2]", {"anyOf": [{"type": "integer"}, {"type": "array"}]}, [1, 2]),+ # discriminated union (object branches only): JSON object is parsed+ (+ '{"kind": "dog"}',+ {"anyOf": [{"type": "object"}, {"type": "integer"}]},+ {"kind": "dog"},+ ),+ # int | list[int] | None: JSON array is parsed+ (+ "[3, 4]",+ {+ "anyOf": [+ {"type": "integer"},+ {"type": "array"},+ {"type": "null"},+ ]+ },+ [3, 4],+ ),+ # plain integer in a non-string union: only arrays/objects are+ # JSON-parsed, so the scalar falls back to the raw string+ ("42", {"anyOf": [{"type": "integer"}, {"type": "array"}]}, "42"),+ ],+ )+ def test_non_string_union_parses_json(self, raw, schema, expected):+ """Unions with no string branch parse arrays/objects as JSON."""+ result = coerce_value(raw, schema)+ assert result == expected++ def test_non_string_union_null_not_accepted_when_not_nullable(self):+ """``null`` in a non-nullable union must not silently return None."""+ schema = {"anyOf": [{"type": "integer"}, {"type": "array"}]}+ result = coerce_value("null", schema)+ assert result is not None++ @pytest.mark.parametrize(+ "schema",+ [+ {"anyOf": [{"type": "string"}, {"type": "null"}]},+ {"type": ["string", "null"]},+ ],+ )+ def test_null_literal_stays_string_when_string_is_nullable(self, schema):+ """``str | None`` keeps ``null`` as the literal string."""+ assert coerce_value("null", schema) == "null"++ def test_one_of_object_union_parses_json(self):+ """Discriminated unions produce ``oneOf``; objects are still decoded."""+ schema = {+ "oneOf": [+ {"type": "object", "properties": {"kind": {"const": "cat"}}},+ {"type": "object", "properties": {"kind": {"const": "dog"}}},+ ]+ }+ assert coerce_value('{"kind": "dog"}', schema) == {"kind": "dog"}++ @pytest.mark.parametrize(+ "branch",+ [{"$ref": "#/$defs/Color"}, {"enum": ["[a]", "b"]}, {}],+ )+ def test_untyped_union_branch_preserves_raw_string(self, branch):+ """A branch without a ``type`` may be a string, so input stays raw."""+ schema = {"anyOf": [{"type": "array"}, branch]}+ assert coerce_value("[a]", schema) == "[a]"++ def test_non_string_union_falls_back_to_string_on_invalid_json(self):+ """When JSON parsing fails for a non-string union, the raw string is returned."""+ schema = {"anyOf": [{"type": "integer"}, {"type": "array"}]}+ result = coerce_value("hello", schema)+ assert result == "hello"+# ---------------------------------------------------------------------------# parse_tool_arguments@@ -653,6 +747,16 @@ def test_named_oauth_server_is_quiet(# ---------------------------------------------------------------------------+class Cat(BaseModel):+ kind: Literal["cat"]+ lives: int = 9+++class Dog(BaseModel):+ kind: Literal["dog"]+ good: bool = True++def _build_test_server() -> FastMCP:"""Create a minimal FastMCP server for integration tests."""server = FastMCP("TestServer")@@ -672,6 +776,21 @@ def _build_test_server() -> FastMCP:"""Sum an optional list of numbers."""return sum(values or [])+ @server.tool+ def union_sum(v: int | list[int]) -> int:+ """Accept an int or a list of ints."""+ return v if isinstance(v, int) else sum(v)++ @server.tool+ def maybe(n: int | None = 5) -> str:+ """Return repr of an optional int."""+ return repr(n)++ @server.tool+ def describe(pet: Annotated[Cat | Dog, Field(discriminator="kind")]) -> str:+ """Describe a pet from a discriminated union."""+ return type(pet).__name__+@server.resource("test://greeting")def greeting_resource() -> str:"""A static greeting resource."""@@ -805,6 +924,51 @@ class TestCallCommandCLI:with pytest.raises(SystemExit):await call_command("fake://server", "")+ @pytest.mark.usefixtures("_patch_client")+ async def test_call_union_no_string_branch_list(+ self, capsys: pytest.CaptureFixture[str]+ ):+ """JSON list is parsed and passed correctly for int|list[int] params."""+ await call_command("fake://server", "union_sum", "v=[1, 2]", json_output=True)+ data = json.loads(capsys.readouterr().out)+ assert data["is_error"] is False+ assert data["structured_content"] == {"result": 3}++ @pytest.mark.usefixtures("_patch_client")+ async def test_call_union_no_string_branch_scalar(+ self, capsys: pytest.CaptureFixture[str]+ ):+ """Plain integer is passed correctly for int|list[int] params."""+ await call_command("fake://server", "union_sum", "v=7", json_output=True)+ data = json.loads(capsys.readouterr().out)+ assert data["is_error"] is False+ assert data["structured_content"] == {"result": 7}++ @pytest.mark.usefixtures("_patch_client")+ async def test_call_nullable_non_string_null(+ self, capsys: pytest.CaptureFixture[str]+ ):+ """``null`` is passed as None for int|None params."""+ await call_command("fake://server", "maybe", "n=null", json_output=True)+ data = json.loads(capsys.readouterr().out)+ assert data["is_error"] is False+ assert data["structured_content"] == {"result": "None"}++ @pytest.mark.usefixtures("_patch_client")+ async def test_call_discriminated_union_object(+ self, capsys: pytest.CaptureFixture[str]+ ):+ """A JSON object reaches a discriminated ``Cat | Dog`` param as a dict."""+ await call_command(+ "fake://server",+ "describe",+ 'pet={"kind": "dog", "good": true}',+ json_output=True,+ )+ data = json.loads(capsys.readouterr().out)+ assert data["is_error"] is False+ assert data["structured_content"] == {"result": "Dog"}+# ---------------------------------------------------------------------------# Structured content serialization