Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

tools: keep explicit Field(title=...) on parameters in the input schema (#5388)

nate nowackaffd31d52a34
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index 4105494f5..7eb320555 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -405,6 +405,7 @@ def search_database(
Field provides several validation and documentation features:
- `description`: Human-readable explanation of the parameter (shown to LLMs)
+- `title`: Short display label for the parameter, for clients that build forms from the schema. FastMCP omits the titles Pydantic derives from parameter names, so a title appears only when it differs from that derived label (`Field(title="Account")` on `account` adds nothing and is omitted).
- `ge`/`gt`/`le`/`lt`: Greater/less than (or equal) constraints
- `min_length`/`max_length`: String or collection length constraints
- `pattern`: Regex pattern for string validation
diff --git a/fastmcp_slim/fastmcp/server/dependencies.py b/fastmcp_slim/fastmcp/server/dependencies.py
index 8c51c9fa2..05b0943b3 100644
--- a/fastmcp_slim/fastmcp/server/dependencies.py
+++ b/fastmcp_slim/fastmcp/server/dependencies.py
@@ -46,7 +46,11 @@ from fastmcp.utilities.async_utils import (
is_coroutine_function,
)
from fastmcp.utilities.logging import get_logger
-from fastmcp.utilities.types import find_kwarg_by_type, is_class_member_of_type
+from fastmcp.utilities.types import (
+ find_kwarg_by_type,
+ get_function_type_hints,
+ is_class_member_of_type,
+)
if TYPE_CHECKING:
from fastmcp.server.context import Context
@@ -789,7 +793,7 @@ def without_injected_parameters(
# this module (dependencies.py) and is read-only, so some Pydantic versions
# can't resolve names like Annotated or Literal from string annotations.
try:
- resolved_hints = get_type_hints(fn, include_extras=True)
+ resolved_hints = get_function_type_hints(fn)
except Exception:
resolved_hints = getattr(fn, "__annotations__", {})
diff --git a/fastmcp_slim/fastmcp/tools/function_parsing.py b/fastmcp_slim/fastmcp/tools/function_parsing.py
index 59fd1e830..760dd3b08 100644
--- a/fastmcp_slim/fastmcp/tools/function_parsing.py
+++ b/fastmcp_slim/fastmcp/tools/function_parsing.py
@@ -335,9 +335,21 @@ class ParsedFunction:
wrapper_fn = without_injected_parameters(fn)
input_type_adapter = get_cached_typeadapter(wrapper_fn)
- input_schema = input_type_adapter.json_schema()
+ raw_input_schema = input_type_adapter.json_schema()
- input_schema = compress_schema(input_schema, prune_titles=True)
+ input_schema = compress_schema(raw_input_schema, prune_titles=True)
+
+ # Pruning drops every title, since Pydantic derives one from each
+ # parameter name. Restore the ones the author wrote with
+ # Field(title=...): those are display labels a client can't rederive.
+ properties = input_schema.get("properties", {})
+ title_from_name = GenerateJsonSchema().get_title_from_name
+ for param_name, raw_property in raw_input_schema.get("properties", {}).items():
+ if param_name not in properties or not isinstance(raw_property, dict):
+ continue
+ title = raw_property.get("title")
+ if isinstance(title, str) and title != title_from_name(param_name):
+ properties[param_name]["title"] = title
# Inject parameter descriptions from the docstring into the schema.
# Explicit annotations (Field(description=...), Annotated[x, "..."])
diff --git a/fastmcp_slim/fastmcp/utilities/types.py b/fastmcp_slim/fastmcp/utilities/types.py
index edd070b81..6a6eba3bf 100644
--- a/fastmcp_slim/fastmcp/utilities/types.py
+++ b/fastmcp_slim/fastmcp/utilities/types.py
@@ -4,10 +4,11 @@ import base64
import inspect
import mimetypes
import os
+import sys
from collections.abc import Callable
from functools import lru_cache
from pathlib import Path
-from types import EllipsisType, UnionType
+from types import EllipsisType, SimpleNamespace, UnionType
from typing import (
Annotated,
Any,
@@ -47,6 +48,29 @@ class FastMCPBaseModel(BaseModel):
model_config = ConfigDict(extra="forbid")
+def get_function_type_hints(fn: Callable[..., Any]) -> dict[str, Any]:
+ """Resolve a function's type hints, keeping `Annotated` metadata.
+
+ Before Python 3.11, `typing.get_type_hints` wraps the hint of every
+ parameter that defaults to `None` in `Optional[...]`. For
+ `Annotated[int | None, Field(title="Limit")] = None` that produces
+ `Optional[Annotated[...]]`, which buries the `Field` metadata in a nested
+ union branch of the JSON schema. Hints are resolved here without that
+ wrapping, so every supported Python version yields the same schema.
+ """
+ if sys.version_info >= (3, 11) or getattr(fn, "__annotations__", None) is None:
+ return get_type_hints(fn, include_extras=True)
+
+ # get_type_hints only adds the Optional wrapper for defaults it reads from
+ # `__code__`, so resolve the annotations through a proxy that has none.
+ namespace_fn = inspect.unwrap(fn)
+ proxy = SimpleNamespace(
+ __annotations__=fn.__annotations__,
+ __globals__=getattr(namespace_fn, "__globals__", {}),
+ )
+ return get_type_hints(proxy, include_extras=True)
+
+
@lru_cache(maxsize=5000)
def get_cached_typeadapter(cls: T) -> TypeAdapter[T]:
"""
@@ -61,7 +85,7 @@ def get_cached_typeadapter(cls: T) -> TypeAdapter[T]:
if hasattr(cls, "__annotations__") and cls.__annotations__:
try:
# Resolve forward references first
- resolved_hints = get_type_hints(cls, include_extras=True)
+ resolved_hints = get_function_type_hints(cls)
except Exception:
# If forward reference resolution fails, use original annotations
resolved_hints = cls.__annotations__
diff --git a/tests/tools/tool/test_title.py b/tests/tools/tool/test_title.py
index fde193f70..95335c8d1 100644
--- a/tests/tools/tool/test_title.py
+++ b/tests/tools/tool/test_title.py
@@ -1,6 +1,10 @@
+from typing import Annotated
+
import pytest
from mcp_types import ToolAnnotations
+from pydantic import Field
+from fastmcp import Client, Context, FastMCP
from fastmcp.tools.base import Tool
@@ -127,3 +131,88 @@ class TestToolTitle:
# Should fall back to annotations.title
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.title == "Annotation Title"
+
+
+class TestParameterTitles:
+ """Explicit Field(title=...) on a parameter reaches the input schema."""
+
+ def test_explicit_title_is_kept(self):
+ def get_bill(
+ account: Annotated[
+ str, Field(title="Account Number", description="The account.")
+ ],
+ ) -> str:
+ return "ok"
+
+ tool = Tool.from_function(get_bill)
+
+ assert tool.parameters["properties"]["account"] == {
+ "description": "The account.",
+ "title": "Account Number",
+ "type": "string",
+ }
+
+ def test_title_from_field_default_is_kept(self):
+ def search(limit: int = Field(10, title="Max Results")) -> str:
+ return "ok"
+
+ tool = Tool.from_function(search)
+
+ assert tool.parameters["properties"]["limit"]["title"] == "Max Results"
+
+ def test_title_on_optional_parameter_is_kept(self):
+ def search(
+ limit: Annotated[int | None, Field(title="Max Results")] = None,
+ ) -> str:
+ return "ok"
+
+ tool = Tool.from_function(search)
+
+ assert tool.parameters["properties"]["limit"] == {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "default": None,
+ "title": "Max Results",
+ }
+
+ def test_title_on_optional_parameter_is_kept_with_context(self):
+ def search(
+ ctx: Context,
+ limit: Annotated[int | None, Field(title="Max Results")] = None,
+ ) -> str:
+ return "ok"
+
+ tool = Tool.from_function(search)
+
+ assert tool.parameters["properties"]["limit"] == {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "default": None,
+ "title": "Max Results",
+ }
+
+ def test_derived_titles_are_still_pruned(self):
+ def get_bill(
+ account: str,
+ account_id: Annotated[int, Field(description="The id.")],
+ title: str = "untitled",
+ ) -> str:
+ return "ok"
+
+ tool = Tool.from_function(get_bill)
+
+ for schema in tool.parameters["properties"].values():
+ assert "title" not in schema
+ assert "title" not in tool.parameters
+
+ async def test_explicit_title_reaches_client(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def get_bill(
+ account: Annotated[str, Field(title="Account Number")],
+ ) -> str:
+ return "ok"
+
+ async with Client(mcp) as client:
+ [tool] = await client.list_tools()
+
+ assert tool.input_schema["properties"]["account"]["title"] == "Account Number"
diff --git a/tests/tools/tool/test_tool.py b/tests/tools/tool/test_tool.py
index b6165cb5e..0aad4445c 100644
--- a/tests/tools/tool/test_tool.py
+++ b/tests/tools/tool/test_tool.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from typing import Annotated
import pytest
from dirty_equals import HasName
@@ -8,7 +9,7 @@ from mcp_types import (
ImageContent,
ToolExecution,
)
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from fastmcp.tools.base import Tool, ToolResult
from fastmcp.utilities.types import Audio, File, Image
@@ -270,6 +271,27 @@ class TestToolFromFunction:
}
)
+ def test_field_metadata_on_none_default_parameter(self):
+ """Annotated metadata stays on the property itself, not a nested branch.
+
+ Python 3.10's `get_type_hints` wraps `None`-defaulted hints in
+ `Optional[...]`, which used to push the description into an inner
+ `anyOf` there.
+ """
+
+ def search(
+ limit: Annotated[int | None, Field(description="How many.")] = None,
+ ) -> str:
+ return "ok"
+
+ tool = Tool.from_function(search)
+
+ assert tool.parameters["properties"]["limit"] == {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "default": None,
+ "description": "How many.",
+ }
+
def test_non_callable_fn(self):
with pytest.raises(TypeError, match="not a callable object"):
Tool.from_function(1) # type: ignore