Skip to content

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

Fix async partial callables rejected by iscoroutinefunction (#3438)

Jeremiah Lowinad517d09fabf
diff --git a/src/fastmcp/experimental/transforms/code_mode.py b/src/fastmcp/experimental/transforms/code_mode.py
index 1ebc3da35..4d7723532 100644
--- a/src/fastmcp/experimental/transforms/code_mode.py
+++ b/src/fastmcp/experimental/transforms/code_mode.py
@@ -1,4 +1,3 @@
-import asyncio
import importlib
import json
from collections.abc import Awaitable, Callable, Sequence
@@ -16,6 +15,7 @@ from fastmcp.server.transforms.search.base import (
serialize_tools_for_output_markdown,
)
from fastmcp.tools.tool import Tool, ToolResult
+from fastmcp.utilities.async_utils import is_coroutine_function
from fastmcp.utilities.versions import VersionSpec
# ---------------------------------------------------------------------------
@@ -38,7 +38,7 @@ DiscoveryToolFactory = Callable[[GetToolCatalog], Tool]
def _ensure_async(fn: Callable[..., Any]) -> Callable[..., Any]:
- if asyncio.iscoroutinefunction(fn):
+ if is_coroutine_function(fn):
return fn
async def wrapper(*args: Any, **kwargs: Any) -> Any:
diff --git a/src/fastmcp/prompts/function_prompt.py b/src/fastmcp/prompts/function_prompt.py
index a58700a01..132c36489 100644
--- a/src/fastmcp/prompts/function_prompt.py
+++ b/src/fastmcp/prompts/function_prompt.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import functools
import inspect
import json
import warnings
@@ -31,7 +32,10 @@ from fastmcp.server.dependencies import (
without_injected_parameters,
)
from fastmcp.server.tasks.config import TaskConfig
-from fastmcp.utilities.async_utils import call_sync_fn_in_threadpool
+from fastmcp.utilities.async_utils import (
+ call_sync_fn_in_threadpool,
+ is_coroutine_function,
+)
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import get_cached_typeadapter
@@ -161,7 +165,7 @@ class FunctionPrompt(Prompt):
task_config.validate_function(fn, func_name)
# if the fn is a callable class, we need to get the __call__ method from here out
- if not inspect.isroutine(fn):
+ if not inspect.isroutine(fn) and not isinstance(fn, functools.partial):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
@@ -312,7 +316,7 @@ class FunctionPrompt(Prompt):
# self.fn is wrapped by without_injected_parameters which handles
# dependency resolution internally
- if inspect.iscoroutinefunction(self.fn):
+ if is_coroutine_function(self.fn):
result = await type_adapter.validate_python(kwargs)
else:
# Run sync functions in threadpool to avoid blocking the event loop
diff --git a/src/fastmcp/resources/function_resource.py b/src/fastmcp/resources/function_resource.py
index bf6673552..5a3f28ee8 100644
--- a/src/fastmcp/resources/function_resource.py
+++ b/src/fastmcp/resources/function_resource.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import functools
import inspect
import warnings
from collections.abc import Callable
@@ -22,7 +23,10 @@ from fastmcp.server.dependencies import (
without_injected_parameters,
)
from fastmcp.server.tasks.config import TaskConfig
-from fastmcp.utilities.async_utils import call_sync_fn_in_threadpool
+from fastmcp.utilities.async_utils import (
+ call_sync_fn_in_threadpool,
+ is_coroutine_function,
+)
if TYPE_CHECKING:
from docket import Docket
@@ -170,7 +174,7 @@ class FunctionResource(Resource):
task_config.validate_function(fn, func_name)
# if the fn is a callable class, we need to get the __call__ method from here out
- if not inspect.isroutine(fn):
+ if not inspect.isroutine(fn) and not isinstance(fn, functools.partial):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
@@ -207,7 +211,7 @@ class FunctionResource(Resource):
"""Read the resource by calling the wrapped function."""
# self.fn is wrapped by without_injected_parameters which handles
# dependency resolution internally
- if inspect.iscoroutinefunction(self.fn):
+ if is_coroutine_function(self.fn):
result = await self.fn()
else:
# Run sync functions in threadpool to avoid blocking the event loop
diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.py
index f7750aea4..ea96af425 100644
--- a/src/fastmcp/resources/template.py
+++ b/src/fastmcp/resources/template.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import functools
import inspect
import re
from collections.abc import Callable
@@ -560,7 +561,7 @@ class FunctionResourceTemplate(ResourceTemplate):
task_config.validate_function(fn, func_name)
# if the fn is a callable class, we need to get the __call__ method from here out
- if not inspect.isroutine(fn):
+ if not inspect.isroutine(fn) and not isinstance(fn, functools.partial):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
diff --git a/src/fastmcp/server/dependencies.py b/src/fastmcp/server/dependencies.py
index 4536b165b..94e244ea7 100644
--- a/src/fastmcp/server/dependencies.py
+++ b/src/fastmcp/server/dependencies.py
@@ -35,7 +35,10 @@ from uncalled_for.resolution import _Depends
from fastmcp.exceptions import FastMCPError
from fastmcp.server.auth import AccessToken
from fastmcp.server.http import _current_http_request
-from fastmcp.utilities.async_utils import call_sync_fn_in_threadpool
+from fastmcp.utilities.async_utils import (
+ call_sync_fn_in_threadpool,
+ is_coroutine_function,
+)
from fastmcp.utilities.types import find_kwarg_by_type, is_class_member_of_type
_logger = logging.getLogger(__name__)
@@ -580,7 +583,7 @@ def without_injected_parameters(fn: Callable[..., Any]) -> Callable[..., Any]:
new_sig = inspect.Signature(user_params)
# Create async wrapper that handles dependency resolution
- fn_is_async = inspect.iscoroutinefunction(fn)
+ fn_is_async = is_coroutine_function(fn)
async def wrapper(**user_kwargs: Any) -> Any:
async with resolve_dependencies(fn, user_kwargs) as resolved_kwargs:
diff --git a/src/fastmcp/server/tasks/config.py b/src/fastmcp/server/tasks/config.py
index 4956a7667..1d5befa2a 100644
--- a/src/fastmcp/server/tasks/config.py
+++ b/src/fastmcp/server/tasks/config.py
@@ -6,12 +6,15 @@ handle task-augmented execution as specified in SEP-1686.
from __future__ import annotations
+import functools
import inspect
from collections.abc import Callable
from dataclasses import dataclass
from datetime import timedelta
from typing import Any, Literal
+from fastmcp.utilities.async_utils import is_coroutine_function
+
# Task execution modes per SEP-1686 / MCP ToolExecution.taskSupport
TaskMode = Literal["forbidden", "optional", "required"]
@@ -124,12 +127,16 @@ class TaskConfig:
# Unwrap callable classes and staticmethods
fn_to_check = fn
- if not inspect.isroutine(fn) and callable(fn):
+ if (
+ not inspect.isroutine(fn)
+ and not isinstance(fn, functools.partial)
+ and callable(fn)
+ ):
fn_to_check = fn.__call__
if isinstance(fn_to_check, staticmethod):
fn_to_check = fn_to_check.__func__
- if not inspect.iscoroutinefunction(fn_to_check):
+ if not is_coroutine_function(fn_to_check):
raise ValueError(
f"'{name}' uses a sync function but has task execution enabled. "
"Background tasks require async functions."
diff --git a/src/fastmcp/tools/function_parsing.py b/src/fastmcp/tools/function_parsing.py
index c5ac20fff..ce519f79e 100644
--- a/src/fastmcp/tools/function_parsing.py
+++ b/src/fastmcp/tools/function_parsing.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import functools
import inspect
import types
from collections.abc import Callable
@@ -157,7 +158,7 @@ class ParsedFunction:
fn_doc = inspect.getdoc(fn)
# if the fn is a callable class, we need to get the __call__ method from here out
- if not inspect.isroutine(fn):
+ if not inspect.isroutine(fn) and not isinstance(fn, functools.partial):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
diff --git a/src/fastmcp/tools/function_tool.py b/src/fastmcp/tools/function_tool.py
index e88828a80..140a2975b 100644
--- a/src/fastmcp/tools/function_tool.py
+++ b/src/fastmcp/tools/function_tool.py
@@ -35,7 +35,10 @@ from fastmcp.tools.tool import (
ToolResult,
ToolResultSerializerType,
)
-from fastmcp.utilities.async_utils import call_sync_fn_in_threadpool
+from fastmcp.utilities.async_utils import (
+ call_sync_fn_in_threadpool,
+ is_coroutine_function,
+)
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import (
NotSet,
@@ -260,7 +263,7 @@ class FunctionTool(Tool):
try:
with anyio.fail_after(self.timeout):
# Thread pool execution for sync functions, direct await for async
- if inspect.iscoroutinefunction(wrapper_fn):
+ if is_coroutine_function(wrapper_fn):
result = await type_adapter.validate_python(arguments)
else:
# Sync function: run in threadpool to avoid blocking
@@ -284,7 +287,7 @@ class FunctionTool(Tool):
) from None
else:
# No timeout: use existing execution path
- if inspect.iscoroutinefunction(wrapper_fn):
+ if is_coroutine_function(wrapper_fn):
result = await type_adapter.validate_python(arguments)
else:
result = await call_sync_fn_in_threadpool(
diff --git a/src/fastmcp/utilities/async_utils.py b/src/fastmcp/utilities/async_utils.py
index aa8caafc7..634d9cfe3 100644
--- a/src/fastmcp/utilities/async_utils.py
+++ b/src/fastmcp/utilities/async_utils.py
@@ -1,6 +1,8 @@
"""Async utilities for FastMCP."""
+import asyncio
import functools
+import inspect
from collections.abc import Awaitable, Callable
from typing import Any, Literal, TypeVar, overload
@@ -10,6 +12,18 @@ from anyio.to_thread import run_sync as run_sync_in_threadpool
T = TypeVar("T")
+def is_coroutine_function(fn: Any) -> bool:
+ """Check if a callable is a coroutine function, unwrapping functools.partial.
+
+ ``inspect.iscoroutinefunction`` returns ``False`` for
+ ``functools.partial`` objects wrapping an async function on Python < 3.12.
+ This helper unwraps any layers of ``partial`` before checking.
+ """
+ while isinstance(fn, functools.partial):
+ fn = fn.func
+ return inspect.iscoroutinefunction(fn) or asyncio.iscoroutinefunction(fn)
+
+
async def call_sync_fn_in_threadpool(
fn: Callable[..., Any], *args: Any, **kwargs: Any
) -> Any:
diff --git a/src/fastmcp/utilities/mcp_server_config/v1/sources/filesystem.py b/src/fastmcp/utilities/mcp_server_config/v1/sources/filesystem.py
index b5e64c8a8..f94dc7c97 100644
--- a/src/fastmcp/utilities/mcp_server_config/v1/sources/filesystem.py
+++ b/src/fastmcp/utilities/mcp_server_config/v1/sources/filesystem.py
@@ -6,6 +6,7 @@ from typing import Any, Literal
from pydantic import Field, field_validator
+from fastmcp.utilities.async_utils import is_coroutine_function
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.sources.base import Source
@@ -182,11 +183,11 @@ class FileSystemSource(Source):
from fastmcp.server.server import FastMCP
# Check if it's a function or coroutine function
- if inspect.isfunction(obj) or inspect.iscoroutinefunction(obj):
+ if inspect.isfunction(obj) or is_coroutine_function(obj):
logger.debug(f"Found factory function '{name}' in {file_path}")
try:
- if inspect.iscoroutinefunction(obj):
+ if is_coroutine_function(obj):
# Async factory function
server = await obj()
else:
diff --git a/tests/utilities/test_async_utils.py b/tests/utilities/test_async_utils.py
new file mode 100644
index 000000000..03177007d
--- /dev/null
+++ b/tests/utilities/test_async_utils.py
@@ -0,0 +1,110 @@
+"""Tests for fastmcp.utilities.async_utils."""
+
+import functools
+
+import pytest
+
+from fastmcp import Client, FastMCP
+from fastmcp.prompts import prompt
+from fastmcp.resources import resource
+from fastmcp.tools import tool
+from fastmcp.utilities.async_utils import is_coroutine_function
+
+
+async def _async_fn(x: int) -> int:
+ return x
+
+
+def _sync_fn(x: int) -> int:
+ return x
+
+
+class TestIsCoroutineFunction:
+ def test_plain_async(self) -> None:
+ assert is_coroutine_function(_async_fn) is True
+
+ def test_plain_sync(self) -> None:
+ assert is_coroutine_function(_sync_fn) is False
+
+ def test_partial_async(self) -> None:
+ p = functools.partial(_async_fn, x=1)
+ assert is_coroutine_function(p) is True
+
+ def test_partial_sync(self) -> None:
+ p = functools.partial(_sync_fn, x=1)
+ assert is_coroutine_function(p) is False
+
+ def test_nested_partial_async(self) -> None:
+ p = functools.partial(functools.partial(_async_fn, x=1))
+ assert is_coroutine_function(p) is True
+
+ def test_nested_partial_sync(self) -> None:
+ p = functools.partial(functools.partial(_sync_fn, x=1))
+ assert is_coroutine_function(p) is False
+
+ def test_lambda(self) -> None:
+ assert is_coroutine_function(lambda: None) is False
+
+ def test_non_callable(self) -> None:
+ assert is_coroutine_function(42) is False
+
+
+class TestAsyncPartialIntegration:
+ async def test_async_partial_tool_runs(self) -> None:
+ async def greet(greeting: str, name: str) -> str:
+ return f"{greeting}, {name}!"
+
+ greet_tool = tool(name="greet")(functools.partial(greet, "Hello"))
+
+ mcp = FastMCP()
+ mcp.add_tool(greet_tool)
+
+ async with Client(mcp) as client:
+ result = await client.call_tool("greet", {"name": "world"})
+ assert result.content[0].text == "Hello, world!"
+
+ async def test_async_partial_resource_reads(self) -> None:
+ async def make_greeting(greeting: str) -> str:
+ return f"{greeting}, resource!"
+
+ greet_resource = resource("test://greet")(
+ functools.partial(make_greeting, "Hi")
+ )
+
+ mcp = FastMCP()
+ mcp.add_resource(greet_resource)
+
+ async with Client(mcp) as client:
+ result = await client.read_resource("test://greet")
+ assert result[0].text == "Hi, resource!"
+
+ async def test_async_partial_prompt_renders(self) -> None:
+ async def make_prompt(prefix: str) -> str:
+ return f"{prefix}: prompt content"
+
+ note_prompt = prompt(name="note")(functools.partial(make_prompt, "Note"))
+
+ mcp = FastMCP()
+ mcp.add_prompt(note_prompt)
+
+ async with Client(mcp) as client:
+ result = await client.get_prompt("note")
+ assert "Note: prompt content" in result.messages[0].content.text
+
+ async def test_async_partial_with_task_true_does_not_raise(self) -> None:
+ async def slow_task(prefix: str, x: int) -> str:
+ return f"{prefix}-{x}"
+
+ slow_tool = tool(name="slow", task=True)(functools.partial(slow_task, "ok"))
+
+ mcp = FastMCP()
+ mcp.add_tool(slow_tool)
+
+ async def test_sync_partial_with_task_true_raises(self) -> None:
+ def sync_task(prefix: str, x: int) -> str:
+ return f"{prefix}-{x}"
+
+ mcp = FastMCP()
+ with pytest.raises(ValueError, match="sync function"):
+ decorated = tool(name="slow", task=True)(functools.partial(sync_task, "ok"))
+ mcp.add_tool(decorated)