π The fast, Pythonic way to build MCP servers and clients.
Name nested fields in detailed CodeMode schemas (#5111)
nate nowack9f983e945b96
diff --git a/docs/servers/transforms/code-mode.mdx b/docs/servers/transforms/code-mode.mdxindex 4f988c63e..10fd8a2e1 100644--- a/docs/servers/transforms/code-mode.mdx+++ b/docs/servers/transforms/code-mode.mdx@@ -122,7 +122,7 @@ CodeMode ships with four built-in discovery tools: `Search`, `GetSchemas`, `GetT| Level | Output | Token cost ||---|---|---|| `"brief"` | Tool names and one-line descriptions | Cheapest β good for scanning |-| `"detailed"` | Compact markdown with parameter names, types, literal values, defaults, and required markers | Medium β often enough to write code |+| `"detailed"` | Compact markdown with parameter names, types, literal values, defaults, required markers, and the field names one level inside any object-valued parameter or return | Medium β often enough to write code || `"full"` | Complete JSON schema | Most expensive β everything |`Search` defaults to `"brief"` and `GetSchemas` defaults to `"detailed"`.@@ -143,7 +143,7 @@ If your tools use [tags](/servers/visibility#tags), Search also accepts a `tags`### GetSchemas-`GetSchemas` returns parameter details for specific tools by name. At its default `"detailed"` level, it renders compact markdown with parameter names, types, literal values, defaults, and required markers. At `"full"`, it returns the complete JSON schema β useful when tools have deeply nested parameters that the compact format doesn't capture.+`GetSchemas` returns parameter details for specific tools by name. At its default `"detailed"` level, it renders compact markdown with parameter names, types, literal values, defaults, and required markers. Object-valued parameters and return values also list their own field names one level down, following `$ref`s into `$defs`, so a tool returning `list[Card]` renders as ``- `items` (object[]): `id`, `url`, `title`, β¦`` rather than an opaque `object[]`. At `"full"`, it returns the complete JSON schema β useful when tools have deeply nested parameters that the compact format doesn't capture.### GetTagsdiff --git a/fastmcp_slim/fastmcp/server/transforms/search/base.py b/fastmcp_slim/fastmcp/server/transforms/search/base.pyindex 6dc12ef47..66e89fb93 100644--- a/fastmcp_slim/fastmcp/server/transforms/search/base.py+++ b/fastmcp_slim/fastmcp/server/transforms/search/base.py@@ -114,6 +114,75 @@ def _schema_type(schema: Any) -> str:return "object" if "properties" in schema else "any"+_NESTED_FIELD_LIMIT = 16+++def _resolve_ref(schema: Any, defs: dict[str, Any]) -> Any:+ """Follow one local `$ref` (`#/$defs/Name`) into `defs`; otherwise return as-is."""+ if isinstance(schema, dict) and isinstance(schema.get("$ref"), str):+ ref = schema["$ref"]+ prefix = "#/$defs/"+ if ref.startswith(prefix):+ return defs.get(ref[len(prefix) :], schema)+ return schema+++def _object_fields(+ schema: Any, defs: dict[str, Any], seen: frozenset[str] = frozenset()+) -> list[str] | None:+ """Field names of the object a schema describes, one level deep, or None.++ Looks through a local `$ref`, an array's `items`, every object branch+ of an `anyOf`/`oneOf` union, and every part of an `allOf`+ composition, so `list[Model]`, `Model | None`, `A | B` and an+ OpenAPI `allOf: [{$ref}, {properties}]` all yield the fields a caller+ may see. Pydantic emits every model as a `$ref` into `$defs`, so+ without this step a typed return renders as `object[]` and the caller+ has to fetch once just to learn the field names.+ """+ if isinstance(schema, dict) and isinstance(schema.get("$ref"), str):+ # A recursive alias (`Json = list[Json] | int`) refers back to itself+ # through anyOf/items; stop at the second visit instead of looping.+ if schema["$ref"] in seen:+ return None+ seen = seen | {schema["$ref"]}+ schema = _resolve_ref(schema, defs)+ if not isinstance(schema, dict):+ return None+ if schema.get("type") == "array":+ return _object_fields(schema.get("items"), defs, seen)+ fields: list[str] = []+ for key in ("anyOf", "oneOf", "allOf"):+ branches = schema.get(key)+ if isinstance(branches, list):+ for branch in branches:+ fields.extend(_object_fields(branch, defs, seen) or [])+ props = schema.get("properties")+ if isinstance(props, dict):+ fields.extend(props)+ unique = list(dict.fromkeys(fields))+ return unique or None+++def _nested_fields(field: Any, defs: dict[str, Any]) -> str:+ """Suffix listing an object-valued field's own field names, or empty.++ Names only: the level below is what turns `items (object[])` into+ something a caller can index, and names cost a fraction of what types or+ descriptions would. On a 51-tool SDK catalog where 44 tools return typed+ pages, this adds ~35% to a detailed render of the whole catalog; a typical+ `get_schema` call covers two or three tools. Long objects are truncated+ with a count.+ """+ fields = _object_fields(field, defs)+ if not fields:+ return ""+ shown = fields[:_NESTED_FIELD_LIMIT]+ rest = len(fields) - len(shown)+ tail = f", +{rest} more" if rest > 0 else ""+ return ": " + ", ".join(f"`{name}`" for name in shown) + tail++def _schema_section(schema: dict[str, Any] | None, title: str) -> list[str]:lines = [f"**{title}**"]if not isinstance(schema, dict):@@ -132,8 +201,11 @@ def _schema_section(schema: dict[str, Any] | None, title: str) -> list[str]:lines.append("*(no parameters)*")return lines+ raw_defs = schema.get("$defs")+ defs = raw_defs if isinstance(raw_defs, dict) else {}for name, field in props.items():- lines.append(f"- {_render_param(name, field, required=name in req)}")+ rendered = _render_param(name, field, required=name in req)+ lines.append(f"- {rendered}{_nested_fields(field, defs)}")return linesdiff --git a/tests/experimental/transforms/test_code_mode.py b/tests/experimental/transforms/test_code_mode.pyindex ff827268c..cfec04ed9 100644--- a/tests/experimental/transforms/test_code_mode.py+++ b/tests/experimental/transforms/test_code_mode.py@@ -1118,6 +1118,40 @@ async def test_code_mode_get_schema_renders_enums_and_defaults() -> None:assert "\u2014" not in text # but no per-parameter description dashes+async def test_code_mode_get_schema_names_return_fields_one_level_down() -> None:+ """A typed return no longer renders as an opaque object[]."""+ from pydantic import BaseModel++ class Note(BaseModel):+ text: str++ class Card(BaseModel):+ id: str+ url: str+ note: Note | None = None++ class Page(BaseModel):+ items: list[Card]+ has_more: bool++ mcp = FastMCP("CodeMode NestedReturns")++ @mcp.tool+ def list_cards() -> Page:+ """List cards."""+ return Page(items=[], has_more=False)++ mcp.add_transform(CodeMode())++ result = await _run_tool(mcp, "get_schema", {"tools": ["list_cards"]})+ unwrapped = _unwrap_result(result)+ text = unwrapped["result"] if isinstance(unwrapped, dict) else unwrapped+ assert "- `items` (object[], required): `id`, `url`, `note`" in text+ assert "- `has_more` (boolean, required)" in text+ # One level only: Note's fields are not expanded under Card.+ assert "`text`" not in text++@pytest.mark.parametrize("content", [[], ["image"]])async def test_error_result_without_text_uses_generic_message(content: list[str],diff --git a/tests/experimental/transforms/test_code_mode_serialization.py b/tests/experimental/transforms/test_code_mode_serialization.pyindex a589ad790..10731476f 100644--- a/tests/experimental/transforms/test_code_mode_serialization.py+++ b/tests/experimental/transforms/test_code_mode_serialization.py@@ -92,6 +92,117 @@ def test_schema_section_lists_fields_with_required_marker() -> None:assert "- `age` (integer)" in lines+def test_schema_section_lists_nested_field_names_through_defs() -> None:+ """Object-valued fields show their own field names one level down."""+ schema = {+ "type": "object",+ "$defs": {+ "Card": {+ "type": "object",+ "properties": {"id": {}, "url": {}, "note": {"$ref": "#/$defs/Note"}},+ },+ "Note": {"type": "object", "properties": {"text": {}}},+ "Page": {+ "type": "object",+ "properties": {"current_page": {}, "has_more": {}},+ },+ },+ "properties": {+ "items": {"type": "array", "items": {"$ref": "#/$defs/Card"}},+ "pagination": {+ "anyOf": [{"$ref": "#/$defs/Page"}, {"type": "null"}],+ "default": None,+ },+ "count": {"type": "integer"},+ "inline": {"type": "object", "properties": {"a": {}, "b": {}}},+ },+ }+ lines = _schema_section(schema, "Returns")+ assert "- `items` (object[]): `id`, `url`, `note`" in lines+ assert "- `pagination` (object?): `current_page`, `has_more`" in lines+ assert "- `count` (integer)" in lines+ assert "- `inline` (object): `a`, `b`" in lines+++def test_schema_section_unions_fields_across_object_branches() -> None:+ """A | B lists the fields of both models; allOf merges inherited and inline fields."""+ schema = {+ "type": "object",+ "$defs": {+ "A": {"type": "object", "properties": {"nested": {}, "shared": {}}},+ "B": {"type": "object", "properties": {"value": {}, "shared": {}}},+ "Base": {"type": "object", "properties": {"id": {}}},+ },+ "properties": {+ "data": {"anyOf": [{"$ref": "#/$defs/A"}, {"$ref": "#/$defs/B"}]},+ "composed": {+ "allOf": [+ {"$ref": "#/$defs/Base"},+ {"type": "object", "properties": {"extra": {}}},+ ]+ },+ },+ }+ lines = _schema_section(schema, "Returns")+ assert "- `data` (object): `nested`, `shared`, `value`" in lines+ assert "- `composed` (object): `id`, `extra`" in lines+++def test_schema_section_stops_on_recursive_refs() -> None:+ """`Json = list[Json] | int` refers to itself through anyOf and items and must not loop."""+ schema = {+ "type": "object",+ "$defs": {+ "Json": {+ "anyOf": [+ {"type": "array", "items": {"$ref": "#/$defs/Json"}},+ {"type": "integer"},+ ]+ },+ "Node": {+ "type": "object",+ "properties": {+ "value": {},+ "children": {"type": "array", "items": {"$ref": "#/$defs/Node"}},+ },+ },+ },+ "properties": {+ "payload": {"$ref": "#/$defs/Json"},+ "tree": {"$ref": "#/$defs/Node"},+ },+ "required": ["payload"],+ }+ lines = _schema_section(schema, "Parameters")+ assert "- `payload` (object, required)" in lines+ assert "- `tree` (object): `value`, `children`" in lines+++def test_schema_section_truncates_long_nested_objects() -> None:+ fields = {f"f{i}": {} for i in range(20)}+ schema = {+ "type": "object",+ "properties": {"row": {"type": "object", "properties": fields}},+ }+ [_, line] = _schema_section(schema, "Returns")+ assert line.endswith("`f15`, +4 more")+++def test_schema_section_ignores_unresolvable_refs() -> None:+ schema = {+ "type": "object",+ "properties": {+ "x": {"$ref": "#/$defs/Missing"},+ "y": {"$ref": "https://example.com/schema.json"},+ },+ }+ assert _schema_section(schema, "Parameters") == [+ "**Parameters**",+ "- `x` (object)",+ "- `y` (object)",+ ]++# ---------------------------------------------------------------------------# serialize_tools_for_output_markdown unit tests# ---------------------------------------------------------------------------