Skip to content

Commit 33bfe60

Browse files
authored
Offload sync function calls to a thread
Offload synchronous function calls to a thread to prevent blocking the event loop. This change ensures that context is correctly propagated using anyio's run_sync.
1 parent 9678a3b commit 33bfe60

1 file changed

Lines changed: 5 additions & 1 deletion

File tree

src/mcp/server/fastmcp/utilities/func_metadata.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,11 @@ async def call_fn_with_arg_validation(
9393
if fn_is_async:
9494
return await fn(**arguments_parsed_dict)
9595
else:
96-
return fn(**arguments_parsed_dict)
96+
return await anyio.to_thread.run_sync(lambda: fn(**arguments_parsed_dict))
97+
# Sync functions are offloaded to a thread to avoid blocking the event loop.
98+
# anyio.to_thread.run_sync() uses copy_context() internally, so contextvars
99+
# propagate correctly. Context is passed explicitly via arguments_parsed_dict,
100+
# not through contextvars, so it is unaffected.
97101

98102
def convert_result(self, result: Any) -> Any:
99103
"""

0 commit comments

Comments
 (0)