Skip to content

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

fix(docstrings): don't leak Returns/Raises into description for parameterless functions (#5067)

Ashfaqf6cfbf7893ba
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index 6c487ad14..98c1203bc 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -319,7 +319,7 @@ You can provide additional metadata about parameters in several ways:
<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:
+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 the first one that recognizes a structured section such as `Args`, `Returns`, or `Raises`:
```python
@mcp.tool
@@ -338,7 +338,7 @@ def process_image(
# 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.
+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. This applies to functions without parameters as well: a docstring with only a `Returns` section yields just the free-form text above it.
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.
diff --git a/fastmcp_slim/fastmcp/utilities/docstring_parsing.py b/fastmcp_slim/fastmcp/utilities/docstring_parsing.py
index 111f37657..c2b295fea 100644
--- a/fastmcp_slim/fastmcp/utilities/docstring_parsing.py
+++ b/fastmcp_slim/fastmcp/utilities/docstring_parsing.py
@@ -34,8 +34,10 @@ 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.
+ recognizes a structured section (parameters, returns, raises, and so on).
+ The description is the free-form text before the first such section. If no
+ parser recognizes a section, returns the full docstring as the description
+ with no parameter descriptions.
"""
doc = inspect.getdoc(fn)
if not doc:
@@ -45,13 +47,18 @@ def parse_docstring(fn: Callable[..., Any]) -> ParsedDocstring:
# keeps its parser and model graph out of ordinary server startup.
from griffe import Docstring, DocstringSectionKind
- # Try each parser and use the first one that finds parameters.
+ # Try each parser and use the first one that recognizes some structure
+ # (parameters, returns, raises, etc.) β€” not just a parameter section.
+ # A parameterless function can still have a Returns/Raises section that
+ # should be split out of the description, same as Args is for functions
+ # that take arguments.
for parser in _PARSERS:
docstring = Docstring(doc, lineno=1, parser=parser)
sections = docstring.parse()
description: str | None = None
parameters: dict[str, str] = {}
+ found_structured_section = False
for section in sections:
if section.kind == DocstringSectionKind.text and description is None:
@@ -59,9 +66,12 @@ def parse_docstring(fn: Callable[..., Any]) -> ParsedDocstring:
elif section.kind == DocstringSectionKind.parameters:
for param in section.value:
parameters[param.name] = param.description
+ found_structured_section = True
+ elif section.kind != DocstringSectionKind.text:
+ found_structured_section = True
- if parameters:
+ if parameters or found_structured_section:
return ParsedDocstring(description=description, parameters=parameters)
- # No parser found parameters β€” return the full docstring unchanged.
+ # No parser recognized any structure β€” return the full docstring unchanged.
return ParsedDocstring(description=doc)
diff --git a/tests/utilities/test_docstring_parsing.py b/tests/utilities/test_docstring_parsing.py
index 8fab08ede..3f3768bc3 100644
--- a/tests/utilities/test_docstring_parsing.py
+++ b/tests/utilities/test_docstring_parsing.py
@@ -1,5 +1,6 @@
"""Tests for docstring-to-schema parameter description extraction."""
+import inspect
from typing import Annotated
from pydantic import Field
@@ -284,6 +285,73 @@ class TestEdgeCases:
# filtering happens at the schema injection level
assert parsed.parameters == {"nonexistent": "Wrong param name."}
+ def test_returns_section_excluded_no_params(self):
+ """A parameterless function's Returns section must not bleed into
+ the description, same as it doesn't for functions with Args."""
+
+ def fn() -> dict[str, bool]:
+ """Return current status.
+
+ Returns:
+ A dict containing the current status.
+ """
+ return {"ok": True}
+
+ parsed = parse_docstring(fn)
+ assert parsed.description == "Return current status."
+ assert parsed.parameters == {}
+
+ def test_raises_section_excluded_no_params(self):
+ def fn() -> None:
+ """Do a thing.
+
+ Raises:
+ ValueError: If something goes wrong.
+ """
+
+ parsed = parse_docstring(fn)
+ assert parsed.description == "Do a thing."
+ assert parsed.parameters == {}
+
+ def test_example_section_excluded_no_params(self):
+ def fn() -> int:
+ """Do a thing.
+
+ Example:
+ fn()
+ """
+ return 1
+
+ parsed = parse_docstring(fn)
+ assert parsed.description == "Do a thing."
+ assert parsed.parameters == {}
+
+ def test_numpy_returns_section_excluded_no_params(self):
+ def fn() -> int:
+ """Do a thing.
+
+ Returns
+ -------
+ int
+ The answer.
+ """
+ return 1
+
+ parsed = parse_docstring(fn)
+ assert parsed.description == "Do a thing."
+ assert parsed.parameters == {}
+
+ def test_prose_without_sections_unchanged_no_params(self):
+ def fn() -> int:
+ """Do a thing.
+
+ Then do another thing, with no section headings.
+ """
+ return 1
+
+ parsed = parse_docstring(fn)
+ assert parsed.description == inspect.getdoc(fn)
+
def test_async_function(self):
async def fn(a: float) -> float:
"""Async summary.
@@ -545,6 +613,18 @@ class TestParsedFunctionIntegration:
# x's description does NOT come from the class's constructor-focused Args
assert "description" not in p.input_schema["properties"]["x"]
+ def test_parameterless_tool_returns_section_excluded(self):
+ def status() -> dict[str, bool]:
+ """Return current status.
+
+ Returns:
+ A dict containing the current status.
+ """
+ return {"ok": True}
+
+ p = ParsedFunction.from_function(status)
+ assert p.description == "Return current status."
+
def test_callable_class_falls_back_to_call_description(self):
"""If the class has no docstring, fall back to __call__'s description."""