Fix Pydantic field alias consistency in structured output

Merged
SJ
1y ago
+46-1

Fix Pydantic field alias consistency in structured output

Summary

Fixes issue #1073. Fix inconsistency between schema and structured output when using Pydantic models with field aliases in tool return types. The schema would display aliased field names but the actual output would use original field names.

Motivation and Context

When defining Pydantic models with field aliases for tool return types, there was an inconsistency where:

  • The output schema would correctly show aliased field names (e.g., "first", "second")
  • The actual structured tool output would use the original field names (e.g., "field_first", "field_second")

This inconsistency made it difficult for clients to reliably consume structured tool outputs, as the field names in the schema didn't match the actual response data.

How Has This Been Tested?

  • Added comprehensive test case test_structured_output_aliases() that verifies both schema generation and output use consistent alias names
  • All existing pytest tests continue to pass

Breaking Changes

No breaking changes. This is a bug fix that makes the behavior consistent with what the schema advertises. Users who were working around this inconsistency may need to update their code to use the aliased field names consistently.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

The fix was a simple one-line change adding by_alias=True to the model_dump() call in func_metadata.py:114. This ensures that when Pydantic models are serialized for structured output, they use the same field names that appear in the generated JSON schema.

The test case covers both the schema generation and the actual output conversion to ensure they remain consistent. This addresses the core issue described in the original bug report where the schema and output used different field naming conventions.

Technical Details

Before the fix:

class Foo(BaseModel):
    field_first: str | None = Field(default=None, alias="first", description="The first field.")
    field_second: str | None = Field(default=None, alias="second", description="The second field.")
  • Schema would show: "first" and "second"
  • Output would contain: "field_first" and "field_second"

After the fix:

  • Both schema and output consistently use: "first" and "second"

Code change:

# Before
structured_content = validated.model_dump(mode="json")

# After  
structured_content = validated.model_dump(mode="json", by_alias=True)