PrefectHQ/fastmcp · error · ValueError

Can not apply name to non-object schema: {name}

Error message

Can not apply name to non-object schema: {name}

What it means

`json_schema_to_type` can only attach a Python class `name` when the top-level schema is an object schema (mapping to a named Pydantic model). If a `name` is supplied for a non-object schema (array, string, number, boolean, ref, etc.) there is no model to name, so it raises ValueError.

Source

Thrown at fastmcp_slim/fastmcp/utilities/json_schema_type.py:237

        class Name:
            name: NameType
        ```
    """
    # Boolean schemas (JSON Schema 2020-12 §4.3.2; also valid since draft-06)
    if schema is True:
        return Any
    if schema is False:
        return _UnsatisfiableType  # type: ignore[return-value]  # ty:ignore[invalid-return-type]

    # Normalise YAML-parsed types (datetime/date → str, non-str keys → str)
    # so that downstream json.dumps/hashing and default values work correctly.
    schema = _normalize_yaml_types(schema)

    # Always use the top-level schema for references
    if schema.get("type") == "object":
        return _object_schema_to_type(schema, schemas=schema, name=name)
    elif name:
        raise ValueError(f"Can not apply name to non-object schema: {name}")
    result = _schema_to_type(schema, schemas=schema)
    return result  # type: ignore[return-value]  # ty:ignore[invalid-return-type]


def _hash_schema(schema: Mapping[str, Any]) -> str:
    """Generate a deterministic hash for schema caching.

    Handles non-JSON-native types (datetime, date, bool keys) that can
    appear in schemas loaded from YAML, which auto-parses date strings.
    Uses ``default=str`` for unserializable values and drops ``sort_keys``
    to avoid ``TypeError`` when dicts mix ``bool`` and ``str`` keys.
    """
    try:
        raw = json.dumps(schema, sort_keys=True, default=str)
    except TypeError:
        # Mixed key types (bool + str) can't be sorted; fall back
        raw = json.dumps(schema, default=str)
    return hashlib.sha256(raw.encode()).hexdigest()

View on GitHub (pinned to 1f02114297)

Solutions

  1. Omit `name` for non-object schemas and let the primitive/array type be generated anonymously.
  2. Wrap the non-object schema: `{'type': 'object', 'properties': {'value': inner_schema}}` and name that.
  3. Ensure your schema root is `{'type': 'object', ...}` when a named model is required.

Example fix

// before
t = json_schema_to_type({'type': 'string'}, name='Name')
// after
t = json_schema_to_type({'type': 'object', 'properties': {'name': {'type': 'string'}}}, name='Name')
Defensive patterns

Strategy: type-guard

Validate before calling

def can_name_schema(schema: dict, name) -> bool:
    return not (name is not None and schema.get('type') != 'object')

Type guard

def is_object_schema(schema: dict) -> bool:
    return isinstance(schema, dict) and schema.get('type') == 'object'

Try / catch

try:
    t = json_schema_to_type(schema, name=name)
except ValueError:
    wrapped = {'type': 'object', 'properties': {'value': schema}, 'required': ['value']}
    t = json_schema_to_type(wrapped, name=name)

Prevention

When it happens

Trigger: `json_schema_to_type({'type': 'array', 'items': {...}}, name='MyList')` or any non-object top-level schema passed with a non-None `name`, e.g. from elicitation handlers or default-parsing helpers.

Common situations: Wrapping tool output/elicitation schemas that are arrays or scalars while forcing a class name; assuming every tool schema is an object.

Understand the failure class

Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.

Related errors


AI-assisted analysis of PrefectHQ/fastmcp@1f02114297 (2026-08-29). Data as JSON: /api/errors/b15a69eedbc54891. Report an issue: GitHub.