[Bug] create_model_from_schema makes fields with explicit non-null defaults nullable
Description
_json_schema_to_pydantic_field() in lib/crewai/src/crewai/utilities/pydantic_schema_utils.py wraps every non-required field in Optional:
if not is_required:
type_ = Optional[type_]
This is wrong for fields that declare an explicit (non-null) default. On the model_json_schema() → create_model_from_schema() round-trip, limit: int = 10 becomes Optional[int] = 10, which silently accepts None and widens the type contract the schema author declared.
This round-trip is a live path: create_model_from_schema is used by StructuredTool/BaseTool args_schema/result_schema checkpoint (de)serialization, Flow state restore, A2A tasks, MCP tool resolution, and project JSON loading.
Steps to reproduce
from crewai.utilities.pydantic_schema_utils import create_model_from_schema
schema = {
"type": "object",
"properties": {
"query": {"type": "string"},
"limit": {"type": "integer", "default": 10},
},
"required": ["query"],
}
Model = create_model_from_schema(schema)
print(Model.model_fields["limit"].annotation) # typing.Optional[int] <- wrong
print(Model(query="x", limit=None)) # accepted, should be rejected
Expected: annotation int, and Model(query="x", limit=None) raises a ValidationError.
Note the inconsistency: the same field listed in required is not wrapped, so its annotation is int. Whether a defaulted field is nullable currently depends only on membership in required, which is unrelated.
Expected behavior
A field with a usable default should keep its declared non-nullable type. Optional is only needed when the field falls back to a None default (no default key, or an explicit default: null).
Suggested fix
- if not is_required:
+ if not is_required and default is None:
type_ = Optional[type_]
Using default is None (rather than checking for the absence of a default key) preserves existing behavior for genuinely nullable schemas such as {"type": ["string", "null"], "default": null}.
I have a patch and regression tests ready (all 97 existing + new pydantic_schema_utils tests pass) and will link a PR to this issue.
Environment
crewAI main @ d7dfa0ef; Python 3.13; pydantic 2.14.3.
This issue was prepared with AI assistance. Per .github/CONTRIBUTING.md, AI-generated issues require the llm-generated label; as an external contributor I cannot set labels myself, so I'm disclosing it here and would appreciate a maintainer adding llm-generated.
#9443 looks like it has this covered. If it stalls for any reason, happy to pick it up — same one-line guard, only wrap in Optional when there's no explicit non-null default, plus the regression test.