diff --git a/src/mcp/server/mcpserver/resources/templates.py b/src/mcp/server/mcpserver/resources/templates.py index 621b2e9448..d48a7fd913 100644 --- a/src/mcp/server/mcpserver/resources/templates.py +++ b/src/mcp/server/mcpserver/resources/templates.py @@ -231,6 +231,9 @@ async def create_resource( if isinstance(result, InputRequiredResult): return result + async def _return_result() -> Any: + return result + return FunctionResource( uri=uri, # type: ignore name=self.name, @@ -240,7 +243,7 @@ async def create_resource( icons=self.icons, annotations=self.annotations, meta=self.meta, - fn=lambda: result, # Capture result in closure + fn=_return_result, ) except (ResourceError, MCPError): raise diff --git a/tests/server/mcpserver/resources/test_resource_template.py b/tests/server/mcpserver/resources/test_resource_template.py index b27c77a585..5848d5c894 100644 --- a/tests/server/mcpserver/resources/test_resource_template.py +++ b/tests/server/mcpserver/resources/test_resource_template.py @@ -520,3 +520,39 @@ def charts(year: str) -> list[_Chart]: template = ResourceTemplate.from_function(charts, uri_template="charts://{year}") assert template.uri_template == "charts://{year}" + + +@pytest.mark.anyio +async def test_template_read_avoids_extra_worker_thread_hop(monkeypatch: pytest.MonkeyPatch) -> None: + """Reading a resource created from a template should not hop to a worker thread just to return the value.""" + import anyio.to_thread + + hops = 0 + real_run_sync = anyio.to_thread.run_sync + + async def counting_run_sync(func: Any, *args: Any, **kwargs: Any) -> Any: + nonlocal hops + hops += 1 + return await real_run_sync(func, *args, **kwargs) + + monkeypatch.setattr(anyio.to_thread, "run_sync", counting_run_sync) + + def sync_user(user_id: str) -> str: + return f"user {user_id}" + + async def async_order(order_id: str) -> str: + return f"order {order_id}" + + sync_template = ResourceTemplate.from_function(fn=sync_user, uri_template="users://{user_id}") + async_template = ResourceTemplate.from_function(fn=async_order, uri_template="orders://{order_id}") + + sync_resource = await sync_template.create_resource("users://1", {"user_id": "1"}, Context()) + assert isinstance(sync_resource, FunctionResource) + assert await sync_resource.read() == "user 1" + assert hops == 1 + + hops = 0 + async_resource = await async_template.create_resource("orders://1", {"order_id": "1"}, Context()) + assert isinstance(async_resource, FunctionResource) + assert await async_resource.read() == "order 1" + assert hops == 0