π The fast, Pythonic way to build MCP servers and clients.
fix(tools): materialize generator transform_fn results in TransformedTool.run (#5672)
εεΊη±³b918dd9845b2
diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.pyindex b9f642c42..34ac102a8 100644--- a/fastmcp_slim/fastmcp/tools/function_tool.py+++ b/fastmcp_slim/fastmcp/tools/function_tool.py@@ -68,6 +68,18 @@ class _ToolBodyError(Exception):"""+def _materialize_sync_generator(result: Any) -> Any:+ """Consume a sync generator into a list, passing any other value through.++ A generator body runs during iteration, not creation, so this must be+ called inside the same invocation the generator was created in β ideally+ on a worker thread, so a blocking body cannot stall the event loop.+ """+ if inspect.isgenerator(result):+ return list(result)+ return result++@lru_cache(maxsize=5000)def _wrap_body_errors(fn: Callable[..., Any], *, materialize_generators: bool = False@@ -94,8 +106,8 @@ def _wrap_body_errors(def wrapper(*args: Any, **kwargs: Any) -> Any:try:result = fn(*args, **kwargs)- if materialize_generators and inspect.isgenerator(result):- return list(result)+ if materialize_generators:+ return _materialize_sync_generator(result)return resultexcept PydanticValidationError as e:raise _ToolBodyError(str(e)) from e@@ -545,9 +557,7 @@ class FunctionTool(Tool):"""if inspect.isasyncgen(result):return [item async for item in result]- if inspect.isgenerator(result):- return list(result)- return result+ return _materialize_sync_generator(result)@overloaddiff --git a/fastmcp_slim/fastmcp/tools/tool_transform.py b/fastmcp_slim/fastmcp/tools/tool_transform.pyindex 16f277299..82f2c326e 100644--- a/fastmcp_slim/fastmcp/tools/tool_transform.py+++ b/fastmcp_slim/fastmcp/tools/tool_transform.py@@ -10,6 +10,7 @@ from typing import Annotated, Any, Literal, castimport mcp_typesfrom mcp_types import ToolAnnotationsfrom pydantic import ConfigDict+from pydantic import ValidationError as PydanticValidationErrorfrom pydantic.fields import Fieldfrom pydantic.functional_validators import BeforeValidatorfrom pydantic.json_schema import SkipJsonSchema@@ -20,6 +21,7 @@ from fastmcp.tools.base import (ToolResult,)from fastmcp.tools.function_parsing import ParsedFunction, _is_object_schema+from fastmcp.tools.function_tool import FunctionTool, _ToolBodyError, _wrap_body_errorsfrom fastmcp.utilities.async_utils import (call_sync_fn_in_threadpool,is_coroutine_function,@@ -361,13 +363,18 @@ class TransformedTool(Tool):try:from fastmcp.server.dependencies import without_injected_parameters- fn = without_injected_parameters(self.fn)- if is_coroutine_function(fn):- result = await fn(**arguments)- else:- result = await call_sync_fn_in_threadpool(fn, **arguments)- if inspect.isawaitable(result):- result = await result+ body_fn = _wrap_body_errors(self.fn, materialize_generators=True)+ fn = without_injected_parameters(body_fn)+ try:+ if is_coroutine_function(fn):+ result = await fn(**arguments)+ else:+ result = await call_sync_fn_in_threadpool(fn, **arguments)+ if inspect.isawaitable(result):+ result = await result+ result = await FunctionTool._materialize_generator(result)+ except PydanticValidationError as exc:+ raise _ToolBodyError(str(exc)) from exc# A multi-round-trip ask (SEP-2322) is not output data: it must# reach the wire handler intact, never reshaped by output_schemadiff --git a/tests/tools/tool_transform/test_generator_execution.py b/tests/tools/tool_transform/test_generator_execution.pynew file mode 100644index 000000000..40b3cc5da--- /dev/null+++ b/tests/tools/tool_transform/test_generator_execution.py@@ -0,0 +1,94 @@+import threading+from collections.abc import AsyncIterator, Iterator+from typing import Literal++import pytest+from pydantic import BaseModel++from fastmcp import Client, Context, FastMCP+from fastmcp.dependencies import Depends+from fastmcp.exceptions import ToolError+from fastmcp.tools import Tool++[email protected]("injection", ["none", "context", "dependency"])+async def test_sync_generator_runs_on_worker(+ injection: Literal["none", "context", "dependency"],+) -> None:+ loop_thread = threading.get_ident()++ def resource() -> int:+ return 7++ def ordinary() -> Iterator[int]:+ assert threading.get_ident() != loop_thread+ yield 7++ def context(ctx: Context) -> Iterator[int]:+ assert isinstance(ctx, Context)+ assert threading.get_ident() != loop_thread+ yield 7++ def dependency(value: int = Depends(resource)) -> Iterator[int]:+ assert threading.get_ident() != loop_thread+ yield value++ def parent() -> list[int]:+ return []++ server = FastMCP()+ fn = {"none": ordinary, "context": context, "dependency": dependency}[injection]+ server.add_tool(+ Tool.from_tool(Tool.from_function(parent), transform_fn=fn, name="test")+ )+ async with Client(server) as client:+ result = await client.call_tool("test", {})+ assert result.data == [7]++[email protected]("asynchronous", [False, True])[email protected]("injected", [False, True])+async def test_generator_body_validation_is_tool_error(+ asynchronous: bool,+ injected: bool,+) -> None:+ class Payload(BaseModel):+ value: int++ def sync_body() -> Iterator[int]:+ yield 1+ Payload.model_validate({"value": "not-an-int"})++ async def async_body() -> AsyncIterator[int]:+ yield 1+ Payload.model_validate({"value": "not-an-int"})++ def sync_context(ctx: Context) -> Iterator[int]:+ assert isinstance(ctx, Context)+ yield from sync_body()++ async def async_context(ctx: Context) -> AsyncIterator[int]:+ assert isinstance(ctx, Context)+ async for item in async_body():+ yield item++ def parent() -> list[int]:+ return []++ functions = {+ (False, False): sync_body,+ (True, False): async_body,+ (False, True): sync_context,+ (True, True): async_context,+ }+ server = FastMCP()+ server.add_tool(+ Tool.from_tool(+ Tool.from_function(parent),+ transform_fn=functions[asynchronous, injected],+ name="test",+ )+ )+ async with Client(server) as client:+ with pytest.raises(ToolError, match="validation error"):+ await client.call_tool("test", {})diff --git a/tests/tools/tool_transform/test_tool_transform.py b/tests/tools/tool_transform/test_tool_transform.pyindex 6238760ae..55135e041 100644--- a/tests/tools/tool_transform/test_tool_transform.py+++ b/tests/tools/tool_transform/test_tool_transform.py@@ -1,7 +1,9 @@"""Core tool transform functionality."""+import asyncioimport jsonimport re+import timefrom dataclasses import dataclassfrom typing import Annotated, Any@@ -907,3 +909,216 @@ async def test_transform_fn_depends_is_resolved():async with Client(mcp) as client:result = await client.call_tool("transformed", {"x": 3})assert result.data == 63+++async def test_transform_fn_sync_generator_yields_values():+ """A sync generator transform_fn's yielded values reach the client.++ A generator body runs during iteration, not creation. FunctionTool+ materializes generator bodies inside the invocation; TransformedTool's+ direct dispatch must do the same or every yielded value is silently+ lost (empty content, empty structured output).+ """+ mcp = FastMCP()++ @mcp.tool+ def base() -> list[str]:+ return []++ def gen_fn():+ yield "a1"+ yield "b1"++ parent = await mcp.get_tool("base")+ assert parent is not None+ mcp.add_tool(Tool.from_tool(parent, name="gen_sync", transform_fn=gen_fn))++ async with Client(mcp) as client:+ result = await client.call_tool("gen_sync", {})+ assert result.data == ["a1", "b1"]+ assert result.structured_content == {"result": ["a1", "b1"]}+++async def test_transform_fn_async_generator_yields_values():+ """An async generator transform_fn's yielded values reach the client.++ Async generator functions are not coroutine functions, so without+ materialization the async generator object is serialized as its repr+ and the structured-content check fails outright.+ """+ mcp = FastMCP()++ @mcp.tool+ def base() -> list[str]:+ return []++ async def gen_fn():+ yield "a1"+ yield "b1"++ parent = await mcp.get_tool("base")+ assert parent is not None+ mcp.add_tool(Tool.from_tool(parent, name="gen_async", transform_fn=gen_fn))++ async with Client(mcp) as client:+ result = await client.call_tool("gen_async", {})+ assert result.data == ["a1", "b1"]+ assert result.structured_content == {"result": ["a1", "b1"]}+++async def test_transform_fn_blocking_sync_generator_does_not_stall_event_loop():+ """A blocking sync generator transform_fn body runs on a worker thread.++ A generator body runs during iteration, not creation, so materializing it+ on the event loop would freeze every concurrent request for the full body+ duration. Like a plain FunctionTool body, it must be consumed inside the+ same threadpool call that created it.+ """+ loop = asyncio.get_running_loop()+ per_item_block = 0.06+ item_count = 5+ total_block = per_item_block * item_count++ def gen_fn():+ for i in range(item_count):+ time.sleep(per_item_block)+ yield f"s{i}"++ mcp = FastMCP()++ @mcp.tool+ def base() -> list[str]:+ return []++ parent = await mcp.get_tool("base")+ assert parent is not None+ mcp.add_tool(Tool.from_tool(parent, name="gen_blocking", transform_fn=gen_fn))++ max_gap = 0.0++ async def heartbeat() -> None:+ nonlocal max_gap+ while True:+ tick = loop.time()+ await asyncio.sleep(0.005)+ max_gap = max(max_gap, loop.time() - tick)++ async with Client(mcp) as client:+ await client.call_tool("gen_blocking", {}) # warm up call machinery+ heartbeat_task = asyncio.create_task(heartbeat())+ try:+ started = loop.time()+ result = await client.call_tool("gen_blocking", {})+ elapsed = loop.time() - started+ finally:+ heartbeat_task.cancel()++ assert result.data == [f"s{i}" for i in range(item_count)]+ # The body really ran to completion for its full blocking duration...+ assert elapsed >= total_block+ # ...but the event loop kept servicing concurrent tasks throughout. With+ # materialization on the event loop the heartbeat stalls for ~total_block;+ # the 1/4 threshold keeps plenty of headroom on a loaded CI runner.+ assert max_gap < total_block / 4+++async def test_transform_fn_generators_are_materialized():+ """Generator transform_fn bodies are consumed like plain tool bodies (#5668)."""++ def gen_sync(**kwargs) -> list[str]: # ty:ignore[invalid-return-type]+ yield "a1"+ yield "a2"++ async def gen_async(**kwargs) -> list[str]: # ty:ignore[invalid-return-type]+ yield "a1"+ yield "a2"++ def parent() -> str:+ return "p"++ parent_tool = Tool.from_function(parent)+ mcp = FastMCP()+ mcp.add_tool(Tool.from_tool(parent_tool, transform_fn=gen_sync, name="t_sync"))+ mcp.add_tool(Tool.from_tool(parent_tool, transform_fn=gen_async, name="t_async"))++ async with Client(mcp) as client:+ # Non-empty generators are materialized to lists+ sync_res = await client.call_tool("t_sync", {})+ assert sync_res.structured_content == {"result": ["a1", "a2"]}+ assert isinstance(sync_res.content[0], TextContent)+ assert sync_res.content[0].text == '["a1","a2"]'++ async_res = await client.call_tool("t_async", {})+ assert async_res.structured_content == {"result": ["a1", "a2"]}+ assert isinstance(async_res.content[0], TextContent)+ assert async_res.content[0].text == '["a1","a2"]'+++async def test_transform_fn_empty_generators():+ """Empty generators are materialized to empty lists (#5668)."""++ def gen_empty(**kwargs) -> list[str]: # ty:ignore[invalid-return-type]+ # Empty generator - no yields, just return+ if False: # type: ignore[unreachable]+ yield++ async def gen_empty_async(**kwargs) -> list[str]: # ty:ignore[invalid-return-type]+ # Empty async generator - no yields, just return+ if False: # type: ignore[unreachable]+ yield++ def parent() -> str:+ return "p"++ parent_tool = Tool.from_function(parent)+ mcp = FastMCP()+ mcp.add_tool(Tool.from_tool(parent_tool, transform_fn=gen_empty, name="t_empty"))+ mcp.add_tool(+ Tool.from_tool(parent_tool, transform_fn=gen_empty_async, name="t_empty_async")+ )++ async with Client(mcp) as client:+ # Empty generators are materialized to empty lists+ empty_res = await client.call_tool("t_empty", {})+ assert empty_res.structured_content == {"result": []}++ empty_async_res = await client.call_tool("t_empty_async", {})+ assert empty_async_res.structured_content == {"result": []}+++async def test_transform_fn_generators_with_context_injection():+ """Generator transform_fn with context injection still materializes (#5668)."""+ mcp = FastMCP()++ @mcp.tool+ def base(x: int) -> int:+ return x++ def gen_with_ctx(x: int, ctx: Context) -> list[int]: # ty:ignore[invalid-return-type]+ assert isinstance(ctx, Context)+ yield x * 2+ yield x * 3++ async def gen_async_with_ctx(x: int, ctx: Context) -> list[int]: # ty:ignore[invalid-return-type]+ assert isinstance(ctx, Context)+ yield x * 2+ yield x * 3++ parent = await mcp.get_tool("base")+ assert parent is not None++ mcp.add_tool(Tool.from_tool(parent, name="t_sync_ctx", transform_fn=gen_with_ctx))+ mcp.add_tool(+ Tool.from_tool(parent, name="t_async_ctx", transform_fn=gen_async_with_ctx)+ )++ async with Client(mcp) as client:+ sync_res = await client.call_tool("t_sync_ctx", {"x": 5})+ assert sync_res.structured_content == {"result": [10, 15]}+ assert isinstance(sync_res.content[0], TextContent)+ assert sync_res.content[0].text == "[10,15]"++ async_res = await client.call_tool("t_async_ctx", {"x": 5})+ assert async_res.structured_content == {"result": [10, 15]}+ assert isinstance(async_res.content[0], TextContent)+ assert async_res.content[0].text == "[10,15]"