π The fast, Pythonic way to build MCP servers and clients.
Extract parameter descriptions from docstrings (#3872)
Jeremiah Lowinf3c00ba1b74a
diff --git a/docs/servers/prompts.mdx b/docs/servers/prompts.mdxindex 41c50ce33..b5cf2f6e9 100644--- a/docs/servers/prompts.mdx+++ b/docs/servers/prompts.mdx@@ -54,7 +54,7 @@ def generate_code_request(language: str, task_description: str) -> list[Message]* **Parameters:** The function parameters define the inputs needed to generate the prompt.* **Inferred Metadata:** By default:* Prompt Name: Taken from the function name (`ask_about_topic`).- * Prompt Description: Taken from the function's docstring.+ * Prompt Description: Taken from the summary of the function's docstring. If the docstring includes parameter descriptions (Google, NumPy, or Sphinx style), they populate each prompt argument's description in the MCP protocol (see [Argument Descriptions](#argument-descriptions)).<Tip>Functions with `*args` or `**kwargs` are not supported as prompts. This restriction exists because FastMCP needs to generate a complete parameter schema for the MCP protocol, which isn't possible with variable argument lists.</Tip>@@ -88,7 +88,7 @@ def data_analysis_prompt(</ParamField><ParamField body="description" type="str | None">- Provides the description exposed via MCP. If set, the function's docstring is ignored for this purpose+ Provides the description exposed via MCP. If set, the function's docstring is ignored for the prompt description, though docstring-derived argument descriptions still apply (see [Argument Descriptions](#argument-descriptions)).</ParamField><ParamField body="tags" type="set[str] | None">@@ -201,6 +201,28 @@ Good choices: `list[int]`, `dict[str, str]`, `float`, `bool`Avoid: Complex Pydantic models, deeply nested structures, custom classes</Warning>+### Argument Descriptions++<VersionBadge version="3.2.4" />++FastMCP parses your function's docstring to extract the prompt description and per-argument descriptions. Google, NumPy, and Sphinx styles are all supported:++```python+def analyze_data(dataset: str, method: str = "summary") -> str:+ """Generate an analysis prompt for a dataset.++ Args:+ dataset: URI or identifier of the dataset to analyze.+ method: Type of analysis to perform (summary, detailed, etc).+ """+ return f"Please perform a '{method}' analysis on {dataset}."+```++The free-form text above the `Args` section β whether a single line or multiple paragraphs β becomes the prompt description, and each argument's docstring entry becomes the description on the corresponding `PromptArgument` in the MCP protocol. Sections like `Returns`, `Raises`, and `Example` are excluded from the description but otherwise ignored.++If an argument already has an explicit description β via `Annotated[x, "..."]` or `Field(description=...)` β that description takes precedence over the docstring. This makes it safe to adopt docstring-based descriptions incrementally: existing annotations keep working, and docstrings fill in the gaps.+### Return ValuesPrompt functions must return one of these types:diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdxindex 91d96d1be..129d0b2dc 100644--- a/docs/servers/tools.mdx+++ b/docs/servers/tools.mdx@@ -36,7 +36,7 @@ def add(a: int, b: int) -> int:When this tool is registered, FastMCP automatically:- Uses the function name (`add`) as the tool name.-- Uses the function's docstring (`Adds two integer numbers...`) as the tool description.+- Parses the function's docstring for the tool description and, if present, per-parameter descriptions (see [Docstring Descriptions](#docstring-descriptions)).- Generates an input schema based on the function's parameters and type annotations.- Handles parameter validation and error reporting.@@ -70,7 +70,7 @@ def search_products_implementation(query: str, category: str | None = None) -> l</ParamField><ParamField body="description" type="str | None">- Provides the description exposed via MCP. If set, the function's docstring is ignored for this purpose+ Provides the description exposed via MCP. If set, the function's docstring is ignored for the tool description, though docstring-derived parameter descriptions still apply (see [Docstring Descriptions](#docstring-descriptions)).</ParamField><ParamField body="tags" type="set[str] | None">@@ -289,6 +289,33 @@ The default flexible validation mode is recommended for most use cases as it hanYou can provide additional metadata about parameters in several ways:+#### Docstring Descriptions++<VersionBadge version="3.2.4" />++FastMCP parses your function's docstring to extract both the tool description and per-parameter descriptions. Google, NumPy, and Sphinx docstring styles are all supported β the parser tries each and uses whichever finds parameter descriptions:++```python+def process_image(+ image_url: str,+ resize: bool = False,+ width: int = 800,+) -> dict:+ """Process an image with optional resizing.++ Args:+ image_url: URL of the image to process.+ resize: Whether to resize the image.+ width: Target width in pixels.+ """+ # Implementation...+```++The free-form text above the `Args` section β whether a single line or multiple paragraphs β becomes the tool description, and each parameter's docstring entry becomes the description for that parameter in the generated schema. Sections like `Returns`, `Raises`, and `Example` are excluded from the description but otherwise ignored.++If a parameter already has an explicit description β via `Annotated[x, "..."]` or `Field(description=...)` β that description takes precedence over the docstring. This makes it safe to adopt docstring-based descriptions incrementally: existing annotations keep working, and docstrings fill in the gaps.+#### Simple String Descriptions<VersionBadge version="2.11.0" />diff --git a/pyproject.toml b/pyproject.tomlindex 7a1d1c084..9aea9be52 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -25,6 +25,7 @@ dependencies = ["jsonref>=1.1.0","uncalled-for>=0.2.0","watchfiles>=1.0.0",+ "griffelib>=2.0.0",]requires-python = ">=3.10"diff --git a/src/fastmcp/prompts/function_prompt.py b/src/fastmcp/prompts/function_prompt.pyindex 63545cb90..872b1c9d7 100644--- a/src/fastmcp/prompts/function_prompt.py+++ b/src/fastmcp/prompts/function_prompt.py@@ -36,6 +36,7 @@ from fastmcp.utilities.async_utils import (call_sync_fn_in_threadpool,is_coroutine_function,)+from fastmcp.utilities.docstring_parsing import ParsedDocstring, parse_docstringfrom fastmcp.utilities.json_schema import compress_schemafrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.types import get_cached_typeadapter@@ -152,11 +153,9 @@ class FunctionPrompt(Prompt):if param.kind == inspect.Parameter.VAR_KEYWORD:raise ValueError("Functions with **kwargs are not supported as prompts")- description = (- metadata.description- if metadata.description is not None- else inspect.getdoc(fn)- )+ # Parse the outer docstring (before unwrapping) to preserve the class+ # docstring as the prompt description for callable class instances.+ outer_docstring = parse_docstring(fn)# Normalize task to TaskConfig and validatetask_value = metadata.task@@ -175,6 +174,24 @@ class FunctionPrompt(Prompt):if isinstance(fn, staticmethod):fn = fn.__func__+ # For callable classes, argument descriptions must come from+ # __call__'s docstring β where the exposed parameters are actually+ # declared. The class docstring's Args section, if any, typically+ # describes __init__, so falling back to it would risk injecting+ # constructor docs into __call__'s arguments on overlapping names.+ # The description, however, comes from the class docstring (which+ # describes what the prompt IS) when present.+ inner_docstring = parse_docstring(fn)+ parsed_docstring = ParsedDocstring(+ description=outer_docstring.description or inner_docstring.description,+ parameters=inner_docstring.parameters,+ )+ description = (+ metadata.description+ if metadata.description is not None+ else parsed_docstring.description+ )+# Transform Context type annotations to Depends() for unified DIfn = transform_context_annotations(fn)@@ -184,6 +201,18 @@ class FunctionPrompt(Prompt):parameters = type_adapter.json_schema()parameters = compress_schema(parameters, prune_titles=True)+ # Inject parameter descriptions from the docstring into the schema.+ # Explicit annotations (Field(description=...), Annotated[x, "..."])+ # already have a "description" key and take precedence.+ if parsed_docstring.parameters:+ properties = parameters.get("properties", {})+ for param_name, param_desc in parsed_docstring.parameters.items():+ if (+ param_name in properties+ and "description" not in properties[param_name]+ ):+ properties[param_name]["description"] = param_desc+# Convert parameters to PromptArgumentsarguments: list[PromptArgument] = []if "properties" in parameters:diff --git a/src/fastmcp/tools/function_parsing.py b/src/fastmcp/tools/function_parsing.pyindex 21d10cb79..9b9b0870e 100644--- a/src/fastmcp/tools/function_parsing.py+++ b/src/fastmcp/tools/function_parsing.py@@ -18,6 +18,7 @@ from fastmcp.server.dependencies import (without_injected_parameters,)from fastmcp.tools.base import ToolResult+from fastmcp.utilities.docstring_parsing import ParsedDocstring, parse_docstringfrom fastmcp.utilities.json_schema import compress_schemafrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.types import (@@ -164,9 +165,9 @@ class ParsedFunction:f"Parameter '{arg_name}' in exclude_args must have a default value.")- # collect name and doc before we potentially modify the function+ # collect name and description before we potentially modify the functionfn_name = getattr(fn, "__name__", None) or fn.__class__.__name__- fn_doc = inspect.getdoc(fn)+ outer_docstring = parse_docstring(fn)# if the fn is a callable class, we need to get the __call__ method from here outif not inspect.isroutine(fn) and not isinstance(fn, functools.partial):@@ -175,6 +176,19 @@ class ParsedFunction:if isinstance(fn, staticmethod):fn = fn.__func__+ # For callable classes, parameter descriptions must come from+ # __call__'s docstring β where the exposed parameters are actually+ # declared. The class docstring's Args section, if any, typically+ # describes __init__, so falling back to it would risk injecting+ # constructor docs into __call__'s schema on overlapping names.+ # The description, however, comes from the class docstring (which+ # describes what the tool IS) when present.+ inner_docstring = parse_docstring(fn)+ parsed_docstring = ParsedDocstring(+ description=outer_docstring.description or inner_docstring.description,+ parameters=inner_docstring.parameters,+ )+# Transform Context type annotations to Depends() for unified DIfn = transform_context_annotations(fn)@@ -195,6 +209,18 @@ class ParsedFunction:input_schema, prune_params=prune_params, prune_titles=True)+ # Inject parameter descriptions from the docstring into the schema.+ # Explicit annotations (Field(description=...), Annotated[x, "..."])+ # already have a "description" key and take precedence.+ if parsed_docstring.parameters:+ properties = input_schema.get("properties", {})+ for param_name, param_desc in parsed_docstring.parameters.items():+ if (+ param_name in properties+ and "description" not in properties[param_name]+ ):+ properties[param_name]["description"] = param_desc+output_schema = None# Get the return annotation from the signaturesig = inspect.signature(fn)@@ -282,7 +308,7 @@ class ParsedFunction:return cls(fn=fn,name=fn_name,- description=fn_doc,+ description=parsed_docstring.description,input_schema=input_schema,output_schema=output_schema or None,return_type=original_output_type,diff --git a/src/fastmcp/utilities/docstring_parsing.py b/src/fastmcp/utilities/docstring_parsing.pynew file mode 100644index 000000000..babcb1e96--- /dev/null+++ b/src/fastmcp/utilities/docstring_parsing.py@@ -0,0 +1,65 @@+"""Extract descriptions from function docstrings.++Uses griffelib to parse Google, NumPy, and Sphinx-style docstrings. The+interface is intentionally narrow β a single function returning a+`ParsedDocstring` β so the implementation can be swapped without touching+callers.+"""++from __future__ import annotations++import inspect+import logging+from collections.abc import Callable+from dataclasses import dataclass, field+from typing import Any++from griffe import Docstring, DocstringSectionKind++_PARSERS = ("google", "numpy", "sphinx")++logger = logging.getLogger("griffe")+# Griffe warns about missing type annotations in docstrings, which is noisy+# and irrelevant β we only care about descriptions.+logger.setLevel(logging.ERROR)+++@dataclass(frozen=True)+class ParsedDocstring:+ """The extracted description and per-parameter descriptions from a docstring."""++ description: str | None = None+ parameters: dict[str, str] = field(default_factory=dict)+++def parse_docstring(fn: Callable[..., Any]) -> ParsedDocstring:+ """Parse a function's docstring into a summary and parameter descriptions.++ Tries Google, NumPy, and Sphinx parsers in order, using the first one that+ successfully extracts parameter descriptions. If none do, returns the full+ docstring as the description with no parameter descriptions.+ """+ doc = inspect.getdoc(fn)+ if not doc:+ return ParsedDocstring()++ # Try each parser and use the first one that finds parameters.+ for parser in _PARSERS:+ docstring = Docstring(doc, lineno=1, parser=parser)+ sections = docstring.parse()++ description: str | None = None+ parameters: dict[str, str] = {}++ for section in sections:+ if section.kind == DocstringSectionKind.text and description is None:+ description = section.value+ elif section.kind == DocstringSectionKind.parameters:+ for param in section.value:+ parameters[param.name] = param.description++ if parameters:+ return ParsedDocstring(description=description, parameters=parameters)++ # No parser found parameters β return the full docstring unchanged.+ return ParsedDocstring(description=doc)diff --git a/tests/prompts/test_prompt.py b/tests/prompts/test_prompt.pyindex ec95126e5..0c7590fea 100644--- a/tests/prompts/test_prompt.py+++ b/tests/prompts/test_prompt.py@@ -430,6 +430,135 @@ class TestPromptArgumentDescriptions:not in arg.description)+ def test_docstring_populates_argument_descriptions(self):+ """Google-style docstrings should populate PromptArgument descriptions."""++ def greet(name: str, topic: str) -> str:+ """Generate a greeting.++ Args:+ name: The person's name.+ topic: The topic to discuss.+ """+ return f"Hello {name}, let's talk about {topic}"++ prompt = Prompt.from_function(greet)++ # Description is summary-only β Args section stripped+ assert prompt.description == "Generate a greeting."++ assert prompt.arguments is not None+ name_arg = next(arg for arg in prompt.arguments if arg.name == "name")+ topic_arg = next(arg for arg in prompt.arguments if arg.name == "topic")+ assert name_arg.description == "The person's name."+ assert topic_arg.description == "The topic to discuss."++ def test_docstring_works_with_numpy_and_sphinx_styles(self):+ def numpy_prompt(a: str) -> str:+ """Do something.++ Parameters+ ----------+ a+ The first argument.+ """+ return a++ def sphinx_prompt(a: str) -> str:+ """Do something.++ :param a: The first argument.+ """+ return a++ numpy = Prompt.from_function(numpy_prompt)+ sphinx = Prompt.from_function(sphinx_prompt)++ for prompt in (numpy, sphinx):+ assert prompt.description == "Do something."+ assert prompt.arguments is not None+ a_arg = next(arg for arg in prompt.arguments if arg.name == "a")+ assert a_arg.description == "The first argument."++ def test_explicit_field_description_overrides_docstring(self):+ """Field(description=...) takes precedence over docstring."""+ from typing import Annotated++ from pydantic import Field++ def greet(+ name: Annotated[str, Field(description="From Field")],+ ) -> str:+ """Greet.++ Args:+ name: From docstring (ignored).+ """+ return f"Hello {name}"++ prompt = Prompt.from_function(greet)+ assert prompt.arguments is not None+ name_arg = next(arg for arg in prompt.arguments if arg.name == "name")+ # Field description wins over the docstring's "From docstring (ignored)".+ # (The existing schema-hint suffix for Annotated params is appended+ # afterwards and is unrelated to precedence.)+ assert name_arg.description is not None+ assert name_arg.description.startswith("From Field")+ assert "From docstring" not in name_arg.description++ def test_explicit_description_keeps_docstring_arg_descriptions(self):+ """Overriding the prompt description does not drop docstring-sourced+ argument descriptions β they come from separate parsing paths."""++ def greet(name: str) -> str:+ """Greet.++ Args:+ name: The person's name.+ """+ return f"Hello {name}"++ prompt = Prompt.from_function(greet, description="Custom description")+ assert prompt.description == "Custom description"+ assert prompt.arguments is not None+ name_arg = next(arg for arg in prompt.arguments if arg.name == "name")+ assert name_arg.description == "The person's name."++ def test_docstring_without_args_section(self):+ """Summary-only docstrings produce a description with no arg descriptions."""++ def greet(name: str) -> str:+ """Just a summary."""+ return f"Hello {name}"++ prompt = Prompt.from_function(greet)+ assert prompt.description == "Just a summary."+ assert prompt.arguments is not None+ name_arg = next(arg for arg in prompt.arguments if arg.name == "name")+ assert name_arg.description is None++ def test_callable_class_sources_description_from_class(self):+ """Class docstring drives the prompt description, while __call__'s+ Args section drives per-argument descriptions (since the arguments+ are __call__'s, not the class's)."""++ class MyPrompt:+ """Class-level description."""++ def __call__(self, name: str) -> str:+ """Internal call doc.++ Args:+ name: From call.+ """+ return f"Hello {name}"++ prompt = Prompt.from_function(MyPrompt())+ assert prompt.description == "Class-level description."+ assert prompt.arguments is not None+ name_arg = next(arg for arg in prompt.arguments if arg.name == "name")+ assert name_arg.description == "From call."+def test_prompt_meta_parameter(self):"""Test that meta parameter is properly handled."""diff --git a/tests/utilities/test_docstring_parsing.py b/tests/utilities/test_docstring_parsing.pynew file mode 100644index 000000000..8fab08ede--- /dev/null+++ b/tests/utilities/test_docstring_parsing.py@@ -0,0 +1,562 @@+"""Tests for docstring-to-schema parameter description extraction."""++from typing import Annotated++from pydantic import Field++from fastmcp.tools.function_parsing import ParsedFunction+from fastmcp.utilities.docstring_parsing import parse_docstring+++class TestGoogleStyle:+ """Google-style docstrings (Args:/Arguments:)."""++ def test_basic(self):+ def fn(a: float, b: float) -> float:+ """Add two numbers.++ Args:+ a: The first number.+ b: The second number.+ """+ return a + b++ parsed = parse_docstring(fn)+ assert parsed.description == "Add two numbers."+ assert parsed.parameters == {+ "a": "The first number.",+ "b": "The second number.",+ }++ def test_with_inline_types(self):+ def fn(a: float, b: str) -> float:+ """Do something.++ Args:+ a (float): The number.+ b (str, optional): The string.+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Do something."+ assert parsed.parameters == {"a": "The number.", "b": "The string."}++ def test_returns_section_excluded(self):+ def fn(a: float) -> float:+ """Summary.++ Args:+ a: The input.++ Returns:+ The output.+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Summary."+ assert parsed.parameters == {"a": "The input."}++ def test_raises_section_excluded(self):+ def fn(a: float) -> float:+ """Summary.++ Args:+ a: The input.++ Raises:+ ValueError: If negative.+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Summary."+ assert parsed.parameters == {"a": "The input."}++ def test_example_section_excluded(self):+ def fn(a: str) -> str:+ """Run some code.++ Example:+ >>> fn("hello")+ 'hello'++ Args:+ a: The input.+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Run some code."+ assert parsed.parameters == {"a": "The input."}++ def test_multiline_param_description(self):+ def fn(a: float) -> float:+ """Summary.++ Args:+ a: A description that+ spans multiple lines.+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Summary."+ assert "spans multiple lines" in parsed.parameters["a"]+++class TestNumpyStyle:+ """NumPy-style docstrings (Parameters\\n----------)."""++ def test_basic(self):+ def fn(x: int, y: int) -> int:+ """Multiply.++ Parameters+ ----------+ x+ The first integer.+ y+ The second integer.+ """+ return x * y++ parsed = parse_docstring(fn)+ assert parsed.description == "Multiply."+ assert parsed.parameters == {+ "x": "The first integer.",+ "y": "The second integer.",+ }++ def test_with_types(self):+ def fn(a: float, b: str) -> float:+ """Do something.++ Parameters+ ----------+ a : float+ The number.+ b : str+ The string.+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Do something."+ assert parsed.parameters == {"a": "The number.", "b": "The string."}+++class TestSphinxStyle:+ """Sphinx-style docstrings (:param name:)."""++ def test_basic(self):+ def fn(name: str, age: int) -> str:+ """Format a greeting.++ :param name: The person's name.+ :param age: The person's age.+ """+ return f"{name} is {age}"++ parsed = parse_docstring(fn)+ assert parsed.description == "Format a greeting."+ assert parsed.parameters == {+ "name": "The person's name.",+ "age": "The person's age.",+ }++ def test_with_type_directive(self):+ def fn(a: float, b: str) -> float:+ """Summary.++ :param a: The number.+ :type a: float+ :param b: The string.+ :type b: str+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Summary."+ assert parsed.parameters == {"a": "The number.", "b": "The string."}+++class TestEdgeCases:+ """Unusual, malformed, or partially-correct docstrings."""++ def test_no_docstring(self):+ def fn(a: int) -> int:+ return a++ parsed = parse_docstring(fn)+ assert parsed.description is None+ assert parsed.parameters == {}++ def test_summary_only(self):+ def fn(a: int) -> int:+ """Just a summary."""+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Just a summary."+ assert parsed.parameters == {}++ def test_multi_paragraph_description(self):+ def fn(a: float) -> float:+ """Summary line.++ More detailed explanation here+ spanning multiple lines.++ Another paragraph.++ Args:+ a: The number.+ """+ return a++ parsed = parse_docstring(fn)+ # Full description (summary + body) should be preserved+ assert parsed.description is not None+ assert "Summary line." in parsed.description+ assert "More detailed explanation" in parsed.description+ assert "Another paragraph." in parsed.description+ # Args section should not bleed into description+ assert "The number" not in parsed.description+ assert parsed.parameters == {"a": "The number."}++ def test_multiline_summary(self):+ def fn(a: float) -> float:+ """Multi-line summary+ continues on next line.++ Args:+ a: The number.+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description is not None+ assert "Multi-line summary" in parsed.description+ assert "continues on next line" in parsed.description+ assert parsed.parameters == {"a": "The number."}++ def test_missing_colon_after_args_keyword(self):+ """Malformed: 'Args' without colon is not a valid section."""++ def fn(a: float) -> float:+ """Summary.++ Args+ a: Maybe the number?+ """+ return a++ parsed = parse_docstring(fn)+ # Parser shouldn't pick this up as an Args section+ assert parsed.parameters == {}++ def test_empty_args_section(self):+ def fn(a: float) -> float:+ """Summary.++ Args:+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.parameters == {}++ def test_param_name_not_in_function_signature(self):+ """Docstring documents a param that doesn't exist on the function."""++ def fn(a: float) -> float:+ """Summary.++ Args:+ nonexistent: Wrong param name.+ """+ return a++ parsed = parse_docstring(fn)+ # parse_docstring returns whatever the docstring says β+ # filtering happens at the schema injection level+ assert parsed.parameters == {"nonexistent": "Wrong param name."}++ def test_async_function(self):+ async def fn(a: float) -> float:+ """Async summary.++ Args:+ a: The number.+ """+ return a++ parsed = parse_docstring(fn)+ assert parsed.description == "Async summary."+ assert parsed.parameters == {"a": "The number."}+++class TestParsedFunctionIntegration:+ """Tests for docstring flowing through ParsedFunction.from_function."""++ def test_description_is_summary_only(self):+ def fn(a: float) -> float:+ """The summary line.++ Args:+ a: Some param.++ Returns:+ Something.+ """+ return a++ p = ParsedFunction.from_function(fn)+ assert p.description == "The summary line."++ def test_param_descriptions_in_schema(self):+ def fn(a: float, b: str) -> str:+ """Do something.++ Args:+ a: The number.+ b: The string.+ """+ return str(a) + b++ p = ParsedFunction.from_function(fn)+ assert p.input_schema["properties"]["a"]["description"] == "The number."+ assert p.input_schema["properties"]["b"]["description"] == "The string."++ def test_numpy_style_integration(self):+ def fn(a: float, b: str) -> str:+ """Summary.++ Parameters+ ----------+ a : float+ The number.+ b : str+ The string.+ """+ return str(a) + b++ p = ParsedFunction.from_function(fn)+ assert p.description == "Summary."+ assert p.input_schema["properties"]["a"]["description"] == "The number."+ assert p.input_schema["properties"]["b"]["description"] == "The string."++ def test_sphinx_style_integration(self):+ def fn(a: float, b: str) -> str:+ """Summary.++ :param a: The number.+ :param b: The string.+ """+ return str(a) + b++ p = ParsedFunction.from_function(fn)+ assert p.description == "Summary."+ assert p.input_schema["properties"]["a"]["description"] == "The number."+ assert p.input_schema["properties"]["b"]["description"] == "The string."++ def test_field_description_takes_precedence(self):+ def fn(+ a: Annotated[float, Field(description="From Field")],+ b: float,+ ) -> float:+ """Add.++ Args:+ a: From docstring.+ b: Also from docstring.+ """+ return a + b++ p = ParsedFunction.from_function(fn)+ assert p.input_schema["properties"]["a"]["description"] == "From Field"+ assert (+ p.input_schema["properties"]["b"]["description"] == "Also from docstring."+ )++ def test_annotated_string_takes_precedence(self):+ def fn(+ a: Annotated[float, "From annotation"],+ b: float,+ ) -> float:+ """Add.++ Args:+ a: From docstring.+ b: Also from docstring.+ """+ return a + b++ p = ParsedFunction.from_function(fn)+ assert p.input_schema["properties"]["a"]["description"] == "From annotation"+ assert (+ p.input_schema["properties"]["b"]["description"] == "Also from docstring."+ )++ def test_no_docstring_no_descriptions(self):+ def fn(a: float) -> float:+ return a++ p = ParsedFunction.from_function(fn)+ assert p.description is None+ assert "description" not in p.input_schema["properties"]["a"]++ def test_docstring_without_args_section(self):+ def fn(a: float) -> float:+ """Just a summary."""+ return a++ p = ParsedFunction.from_function(fn)+ assert p.description == "Just a summary."+ assert "description" not in p.input_schema["properties"]["a"]++ def test_partial_params_documented(self):+ """Only some params documented β others remain undescribed."""++ def fn(a: float, b: float, c: float) -> float:+ """Add numbers.++ Args:+ a: Documented.+ """+ return a + b + c++ p = ParsedFunction.from_function(fn)+ assert p.input_schema["properties"]["a"]["description"] == "Documented."+ assert "description" not in p.input_schema["properties"]["b"]+ assert "description" not in p.input_schema["properties"]["c"]++ def test_nonexistent_param_in_docstring_ignored(self):+ """Docstring mentions a param that doesn't exist β silently skipped."""++ def fn(a: float) -> float:+ """Summary.++ Args:+ a: The real one.+ ghost: Doesn't exist.+ """+ return a++ p = ParsedFunction.from_function(fn)+ assert p.input_schema["properties"]["a"]["description"] == "The real one."+ # No crash, no ghost in properties+ assert "ghost" not in p.input_schema["properties"]++ def test_types_in_docstring_dont_override_schema_types(self):+ """A '(str)' in the docstring must not change the schema's type."""++ def fn(a: float) -> float:+ """Summary.++ Args:+ a (str): A description, but the type is wrong.+ """+ return a++ p = ParsedFunction.from_function(fn)+ # Schema type comes from the annotation, not the docstring+ assert p.input_schema["properties"]["a"]["type"] == "number"+ assert (+ p.input_schema["properties"]["a"]["description"]+ == "A description, but the type is wrong."+ )++ def test_multi_paragraph_description_preserved(self):+ def fn(a: float) -> float:+ """Short summary.++ A longer explanation that provides+ additional context.++ Args:+ a: The number.+ """+ return a++ p = ParsedFunction.from_function(fn)+ assert p.description is not None+ assert "Short summary" in p.description+ assert "longer explanation" in p.description+ assert "The number" not in p.description++ def test_async_function_integration(self):+ async def fn(a: float) -> float:+ """Async summary.++ Args:+ a: The number.+ """+ return a++ p = ParsedFunction.from_function(fn)+ assert p.description == "Async summary."+ assert p.input_schema["properties"]["a"]["description"] == "The number."++ def test_callable_class_sources_description_from_class(self):+ """Class docstring drives the tool description (it describes what the+ tool IS), while __call__'s Args section drives parameter descriptions+ (its params are what the schema actually exposes)."""++ class MyTool:+ """Class-level description."""++ def __call__(self, x: int) -> int:+ """Internal call doc.++ Args:+ x: From call.+ """+ return x++ p = ParsedFunction.from_function(MyTool())+ # Class docstring wins for the description+ assert p.description == "Class-level description."+ # __call__'s Args wins for the parameter description+ assert p.input_schema["properties"]["x"]["description"] == "From call."++ def test_callable_class_does_not_inherit_class_param_descriptions(self):+ """The class docstring's Args section typically describes __init__.+ Even when param names overlap with __call__, those descriptions must+ not leak into __call__'s parameter schema."""++ class MyTool:+ """Describes what the tool does.++ Args:+ x: Constructor argument (should NOT appear on __call__'s x).+ """++ def __init__(self, x: str) -> None:+ self.x = x++ def __call__(self, x: int) -> int:+ return x++ p = ParsedFunction.from_function(MyTool("config"))+ assert p.description == "Describes what the tool does."+ # x's description does NOT come from the class's constructor-focused Args+ assert "description" not in p.input_schema["properties"]["x"]++ def test_callable_class_falls_back_to_call_description(self):+ """If the class has no docstring, fall back to __call__'s description."""++ class MyTool:+ def __call__(self, x: int) -> int:+ """Call-level description.++ Args:+ x: From call.+ """+ return x++ p = ParsedFunction.from_function(MyTool())+ assert p.description == "Call-level description."+ assert p.input_schema["properties"]["x"]["description"] == "From call."diff --git a/uv.lock b/uv.lockindex ecdefcde8..b16e6865d 100644--- a/uv.lock+++ b/uv.lock@@ -830,6 +830,7 @@ dependencies = [{ name = "authlib" },{ name = "cyclopts" },{ name = "exceptiongroup" },+ { name = "griffelib" },{ name = "httpx" },{ name = "jsonref" },{ name = "jsonschema-path" },@@ -914,6 +915,7 @@ requires-dist = [{ name = "cyclopts", specifier = ">=4.0.0" },{ name = "exceptiongroup", specifier = ">=1.2.2" },{ name = "google-genai", marker = "extra == 'gemini'", specifier = ">=1.18.0" },+ { name = "griffelib", specifier = ">=2.0.0" },{ name = "httpx", specifier = ">=0.28.1,<1.0" },{ name = "jsonref", specifier = ">=1.1.0" },{ name = "jsonschema-path", specifier = ">=0.3.4" },@@ -1021,6 +1023,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/dc/82/fcb6520612bec0c39b973a6c0954b6a0d948aadfe8f7e9487f60ceb8bfa6/googleapis_common_protos-1.73.1-py3-none-any.whl", hash = "sha256:e51f09eb0a43a8602f5a915870972e6b4a394088415c79d79605a46d8e826ee8", size = 297556, upload-time = "2026-03-26T22:15:58.455Z" },]+[[package]]+name = "griffelib"+version = "2.0.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/9d/82/74f4a3310cdabfbb10da554c3a672847f1ed33c6f61dd472681ce7f1fe67/griffelib-2.0.2.tar.gz", hash = "sha256:3cf20b3bc470e83763ffbf236e0076b1211bac1bc67de13daf494640f2de707e", size = 166461, upload-time = "2026-03-27T11:34:51.091Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/11/8c/c9138d881c79aa0ea9ed83cbd58d5ca75624378b38cee225dcf5c42cc91f/griffelib-2.0.2-py3-none-any.whl", hash = "sha256:925c857658fb1ba40c0772c37acbc2ab650bd794d9c1b9726922e36ea4117ea1", size = 142357, upload-time = "2026-03-27T11:34:46.275Z" },+]+[[package]]name = "grpcio"version = "1.78.0"