Skip to content

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

Run sync resource templates in the threadpool (#5742)

Marcus Changc20666ca0501
diff --git a/fastmcp_slim/fastmcp/resources/template.py b/fastmcp_slim/fastmcp/resources/template.py
index a779ffc8e..1c8baf467 100644
--- a/fastmcp_slim/fastmcp/resources/template.py
+++ b/fastmcp_slim/fastmcp/resources/template.py
@@ -30,6 +30,10 @@ from fastmcp.resources.security import (
InheritSecurity,
ResourceSecurity,
)
+from fastmcp.utilities.async_utils import (
+ call_sync_fn_in_threadpool,
+ is_coroutine_function,
+)
from fastmcp.utilities.authorization import AuthCheck
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.json_schema import compress_schema
@@ -633,10 +637,15 @@ class FunctionResourceTemplate(ResourceTemplate):
raise
# self.fn is wrapped by without_injected_parameters which handles
- # dependency resolution internally, so we call it directly
- result = self.fn(**kwargs)
- if inspect.isawaitable(result):
- result = await result
+ # dependency resolution internally
+ if is_coroutine_function(self.fn):
+ result = await self.fn(**kwargs)
+ else:
+ # Run sync functions in threadpool to avoid blocking the event loop
+ result = await call_sync_fn_in_threadpool(self.fn, **kwargs)
+ # Handle sync wrappers that return awaitables (e.g., partial(async_fn))
+ if inspect.isawaitable(result):
+ result = await result
return result
diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.py
index e93beb1a9..347165a87 100644
--- a/tests/resources/test_resource_template.py
+++ b/tests/resources/test_resource_template.py
@@ -1,4 +1,6 @@
+import asyncio
import functools
+import threading
from typing import Annotated
from urllib.parse import quote
@@ -243,6 +245,25 @@ class TestResourceTemplate:
result = await resource.read()
assert result == b"test"
+ async def test_sync_template_runs_concurrently(self):
+ """Sync template functions run in the threadpool and don't block each other."""
+ num_calls = 3
+ barrier = threading.Barrier(num_calls, timeout=0.5)
+
+ def concurrent_template(id: str) -> str:
+ barrier.wait()
+ return id
+
+ template = ResourceTemplate.from_function(
+ fn=concurrent_template, uri_template="data://{id}"
+ )
+
+ # Raises BrokenBarrierError if the reads run one at a time on the loop
+ results = await asyncio.gather(
+ *(template.read(arguments={"id": str(i)}) for i in range(num_calls))
+ )
+ assert results == [str(i) for i in range(num_calls)]
+
async def test_basemodel_conversion(self):
"""Test handling of BaseModel types."""